Home  >  Article  >  Web Front-end  >  javascript dynamically generate private variable accessor_javascript skills

javascript dynamically generate private variable accessor_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:40:141058browse

Copy code The code is as follows:

//Create a new user object and accept a Objects with many properties as parameters
function User(properties)
{
//Traverse all properties of the object and ensure that their scope is correct
for(var i in properties){
(function(which){
var p=i;
//Create a new reader (getter) for this property
which["get" p]=function(){
return properties[p];
};

//Create a new setter (setter) for this property
which["set" p]=function(val)
{
properties[p]=val;
};
})(this);
}
}
//Create a new user object instance and add two An object of the attribute is passed in as a parameter
var user=new User({name:"Bob",age:44});
//Read the attribute value
alert(user.getname()) ;
//Set attribute value
user.setage(23);
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