An example is incorrect. Modified it. Below is my understanding!
This is what I wrote in the book. I added some annotations: Function User (props ){
For ( VaR Prop In Props ){
( Function (Currentobj ){ // The currentobj here is passed by this. This is user
Alert (currentobj. constructor ); // It can be seen 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: // ********************* *
// Props object, such as: {"name": "chengkai", "Age": 22}
// **************************************** ********
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
}
}
VaRUser= NewUser ({"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!