JavaScript closure examples explained_javascript skills
May 16, 2016 pm 04:51 PMThe 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.
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 .
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
Let’s continue looking at an example of constructor calling.
Copy code
MyObj.prototype.getStatus = function(){
return this.status;
};
var obj = new MyObj("javascript");
obj.getStatus(); // "javascript"
Copy code
}
};
};
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.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What is the meaning of closure in C++ lambda expression?

How to implement closure in C++ Lambda expression?

What are the advantages and disadvantages of closures in C++ functions?

Solve the memory leak problem caused by closures

The impact of function pointers and closures on Golang performance

How are closures implemented in Java?

Chained calls and closures of PHP functions

Summary of the advantages and disadvantages of golang anonymous functions and closures
