Home >Web Front-end >JS Tutorial >JavaScript closure examples explained_javascript skills

JavaScript closure examples explained_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:51:421081browse

The benefit of this is that inner functions can access the parameters and variables of the outer function in which they are defined.

First, let’s construct a simple object.

Copy code The code is as follows:

var testObj = {
value: 10,
add: function(inc){
this.value = (typeof inc === "number") ? inc : 1;
}
};

testObj.add();
testObj.value; // 11

testObj.add(2);
testObj.value; // 13


There is a problem with writing this way. The value cannot be guaranteed not to be illegally modified. It can be modified as follows .
Copy code The code is as follows:

var testObj = (function(){
var value = 10;
return {
add: function(inc){
value = (typeof inc === "number") ? inc : 1;
},
getValue: function (){
              return value;
testObj.add();
testObj.getValue(); // 11
testObj.add(2);

testObj.getValue(); // 13

We can generally call a function to initialize testObj. The function will return an object literal. The function A value variable is defined here, which is always available to the add and getValue methods, but the scope of the function makes it invisible to other programs. At the same time, we can also draw a conclusion that the internal function has a longer life cycle than its external function.


Let’s continue looking at an example of constructor calling.



Copy code

The code is as follows:var MyObj = function(str){ this .status = str;
};

MyObj.prototype.getStatus = function(){
return this.status;
};

var obj = new MyObj("javascript");
obj.getStatus(); // "javascript"

There is nothing wrong with writing this, but it will be a bit "unnecessary", why? What about using a getStatus method to access a property that can be accessed directly? Of course it only makes sense if status is a private property.




Copy code
The code is as follows:var obj = function(status){ return {
getStatus: function(){
return status;
}
};
};

var myObj = obj("javascript");
myObj.getStatus(); // "javascript"
Here when we call obj, it returns a new object containing the getStatus method , a reference to the object is saved in myObj, even if obj has been returned, the getStatus method still enjoys the privilege of accessing the status attribute of the obj object. The getStatus method does not access a copy of the parameter, it accesses the parameter itself. This is possible because the function has access to the context in which it was created, which is called a closure.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn