gpt4 book ai didi

javascript - 为什么这些 JavaScript 函数不添加到该对象中?

转载 作者:行者123 更新时间:2023-11-28 13:40:28 25 4
gpt4 key购买 nike

我想为基于 Json 文件的对象编写 getter 和 setter 函数。我复制了 John Resig 的书(Appress Pro JavaScript Techniques)中的以下代码,但它不起作用,并且这些函数没有添加到对象中。你能告诉我为什么以及正确的代码是什么吗?

// Create a new user object that accepts an object of properties
function User(properties) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
for (var i in properties) {
(function () {
// Create a new getter for the property
this["get" + i] = function () {
return properties[i];
};

// Create a new setter for the property
this["set" + i] = function (val) {
properties[i] = val;
};
})();
}
}

// Create a new user object instance and pass in an object of
// properties to seed it with
var user = new User({
name: "Bob",
age: 44
});

// Just note that the name property does not exist, as it's private
// within the properties object
//alert( user.name == null );

// However, we're able to access its value using the new getname()
// method, that was dynamically generated
alert(user.getname());

最佳答案

您使用了一个函数来创建一个闭包,但您忘记将 i 传递给它。您还需要在函数内对 this 进行不同的引用,因为其中的上下文会更改为 window

function User(properties) {
var i, me = this;
for (i in properties) (function (i) {
// Create a new getter for the property
me["get" + i] = function () { // using `me` because `this !== me`
return properties[i];
};

// Create a new setter for the property
me["set" + i] = function (val) {
properties[i] = val;
};
}(i)); // i passed into function closure
}

关于javascript - 为什么这些 JavaScript 函数不添加到该对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18184043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com