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

标签 javascript json anonymous-function getter-setter

我想为基于 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/

相关文章:

javascript - getJSON 并使用 $.each 循环

c# - 不能通过委托(delegate)

javascript - 使用 each() 选择并计算未选中复选框的长度

javascript - 将 Ctrl 中的 switch 语句减少为禁用输入字段(AngularJS)

json - 使用 Zend Framework 2 将 Doctrine 2 实体持久集合转换为数组的最佳方法

json - 如何在 swift 中使用 json 进行 HTTPRequest

jquery - 在 Javascript/jQuery 中将匿名函数传递给自定义事件触发器

JavaScript:将更改参数传递给回调

javascript - setTimeout 和递归 IFFE,嵌套!?如何计算延迟。

javascript - 如何解决报告的攻击页面