The benefit of this is that internal functions can access parameters and variables that define their external functions.
First, let's construct a simple object.
Copy Code code 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 this writing, the value can not be guaranteed not to be illegally modified, you may follow the following methods to modify.
Copy Code code 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 invoke the form of a function to initialize testobj, which returns an object literal, a value variable defined in a function that 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 conclude that the intrinsic function has a longer life cycle than its external function.
Let's go on to see an example of a constructor call.
Copy Code code as follows:
var myobj = function (str) {
This.status = str;
};
MyObj.prototype.getStatus = function () {
return this.status;
};
var obj = new MyObj ("JavaScript");
Obj.getstatus (); "JavaScript"
This is not wrong, but there is a little "superfluous", why use a GetStatus method to access a property that can be accessed directly? If status is a private property, then of course it makes sense.
Copy Code code 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 that is kept in myobj, even if obj has returned, but the GetStatus method still has the privilege of accessing the Status property 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 can access the context in which it was created, which is called a closure.