An example in the book of the Helper House (www.bkjia.com) is incorrect. Modified it. Below is my understanding! This is what I wrote in the book. I added some annotations:
Reference content is as follows:
Function User (props ){
For (var prop in props ){
(Function (currentObj) {// The currentObj here is passed by this. This is User
Alert (currentObj. constructor); // You Can See That currentObj is User
// Create a new getter (Reader) for this attribute)
CurrentObj ["get" + prop] = function (){
// Alert (props. name + "" + props. age + "" + prop );
Return props [prop];
}
// Create a new setter for this attribute (setter)
CurrentObj ["set" + prop] = function (val ){
Props [prop] = val;
};
}) (This); // here this is the User
}
}
Var user = new User ({"name": "chengkai", "age": 22 });
// Note that the name attribute does not exist because it is a private variable of the property object (props Obj ).
Alert (user. name = null); // Output true
Alert (user. getname (); // output 22
Alert (user. getage (); // output 22 |
As above: Why is the output 22 like this? Haha. Here is the closure problem !!
Correction:
|
Reference content is as follows:
// **************** Dynamic generation method ******************* ***
// Props object, such as: {"name": "chengkai", "age": 22}
// Fire station long network, http://www.liehuo.org/
//************************************** **********
Function User (props ){
For (var prop in props ){
(Function (currentObj) {// The currentObj here is passed by this. This is User
// Create a new getter (Reader) for this attribute)
(Function (prop ){
CurrentObj ["get" + prop] = function (){
// Alert (props. name + "" + props. age + "" + prop );
Return props [prop];
}
// Create a new setter for this attribute (setter)
CurrentObj ["set" + prop] = function (val ){
Props [prop] = val;
};
}) (Prop );
}) (This); // here this is the User
}
}
Var user = new User ({"name": "chengkai", "age": 22 });
// Note that the name attribute does not exist because it is a private variable of the property object (props Obj ).
Alert (user. name = null); // Output true
Alert (user. getname (); // output chengkai
User. setage (11 );
User. setname ("kai ");
Alert (user. getage (); // output 11
Alert (user. getname (); // output kai
|
Pay attention to the differences before and after, and understand the application of the above anonymous function. It should be nice to see what's going on!