比较两段代码的不同之处:
function Comment(properties){
for(var attr in properties){
(function(){
this['get'+attr] = function(){
return properties[attr];
};
this['set'+attr] = function(value){
properties[attr] = value;
}
})();
}
}
var test = new Comment({name:'xuyi',sex:'boy'});
alert(test.getname());
test.setname("nobody");
alert(test.getname());
alert(test.getsex());
function Comment(properties){
for(var attr in properties){
(function(scope){
var p = attr;
scope['get'+p] = function(){
return properties[p];
};
scope['set'+p] = function(value){
properties[p] = value;
}
})(this);
}
}
var test = new Comment({name:'xuyi',sex:'boy'});
alert(test.getname());
test.setname("nobody");
alert(test.getname());
alert(test.getsex());
第一段是错误的:
1、没有为匿名函数传递正确的上下文。匿名函数的上下文this=window
2、没有在闭包中设置变量保存for 循环中计数器变量attr的状态