哪位大侠愿意拔刀相助
这是一段js代码
function User(properties) {
for (var i in properties) {
var p=i;
(function (which) {
which['get' + p] = function () {
return properties[p];
};
which['set' + p] = function (val) {
properties[p] = val;
};
})(this);
}
}
var user = new User({ "name": 'Mike', "age": 27 });
user.setname('Nike');
alert(user.getage());
alert(user.getname());
为什么alert(user.getage());得到的还是‘Nike’?
------解决方案--------------------
function User(properties) {
for (var i in properties) {
var p=i;
(function (which, p) {
which['get' + p] = function () {
return properties[p];
};
which['set' + p] = function (val) {
properties[p] = val;
};
})(this, p);
}
}
var user = new User({ "name": 'Mike', "age": 27 });
你说的问题不存在
帮你修改的是一个闭包问题