1. Closures
The closure in js is a function (a closed package structure or space that is not open to the outside world)
The data inside the function cannot be accessed outside the function
To be solved The problem is that the data inside the function needs to be accessed indirectly from the outside
function outer(){ var data = "数据"; return function(){ return data; } }
function outer(){ var data = "数据"; return { getData:function(){ return data; }, setData:function(value){ data = value; return data; } } }
由于js是单线程执行的,会先执行主任务,然后执行次要任务(包括setTimeOut和setInterval中的回调函数中的代码)
For example:
for(var i = 0 ; i < 10; i++){ setTimeout(function(){ console.log(i); },0); }
will not print out 1~10 as expected, but print out 10 10 because the for loop will not be executed until it is executed. setTimeout callback function, if the time is up, execute
for(var i = 0; i< 3; i++){ function foo(j){ return function(){ console.log(j); }; } var f = foo(i); setTimeout(f, 0); }
It will be printed as 1 2 3
Closures share the same function definition, but save different lexical environments
function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; }var size12 = makeSizer(12);var size14 = makeSizer(14);var size16 = makeSizer(16); document.getElementById('size-12').onclick = size12; document.getElementById('size-14').onclick = size14; document.getElementById('size-16').onclick = size16;
The text will change when clicked12, 14, 16
But if you change the writing:
function makeSizer(size) { document.body.style.fontSize = size + 'px'; }
If written like this, the text size is all 12, because they share the same lexical environment. After the first one is executed, the following and the previous ones share the same lexical environment
When creating a new object or class, methods should usually be associated with the object's prototype rather than being defined in the object's constructor. The reason is that this will cause the method to be reassigned every time the constructor is called (that is, every object is created).
For example, we can write like this:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };
Related recommendations:
Detailed explanation of the use of js closure-js tutorial
Detailed introduction to the in-depth analysis of Javascript closure and code implementation method
The above is the detailed content of Detailed explanation of application code of js closure and prototype. For more information, please follow other related articles on the PHP Chinese website!