【问题标题】:Constructor method can't access nested properties of a child object in a for loop构造函数方法无法访问 for 循环中子对象的嵌套属性
【发布时间】:2015-07-20 20:42:54
【问题描述】:
function myConstructor (arg) {
    this.myName = arg;
    this.totalNumber = 0;
    this.foo = {
        bar: {
            someBoolean: false,
            someNumber: 5
        },
        baz: {
            someBoolean: false,
            someNumber: 10
        }
    };
}

myConstructor.prototype.getNumber = function () {
    console.log(this); //successfully returns the child object

    for (var i in this.foo) {
        //console log tests
        console.log(this); //still returns the child object with all properties, including the myName 'whatever'
        console.log(this.foo); //returns the 'foo' object with all nested properties
        console.log(i); //returns 'bar' and 'baz', respectively
        console.log(this.foo.hasOwnProperty(i)); //returns true

        //where it all goes wrong
        console.log(typeof(i)); //returns 'string'
        console.log(this.foo.i); //returns undefined, even though 'this.foo' definitely has 'bar' and 'baz' properties

        //what I'm trying to accomplish
        /*
        if (this.foo.i.hasOwnProperty('someBoolean') && this.foo.i.someBoolean === true) {
            this.totalNumber += this.foo.i.someNumber;
        } //returns 'TypeError: Cannot read property 'hasOwnProperty' of undefined
        */
    }
    return this.totalNumber;
};

var myChild = new myConstructor('whatever');
myChild.getNumber();

我想要完成的是使用构造函数来创建一个孩子。在该子对象内部具有嵌套对象,具有我稍后将在我的代码中更改的各种属性。然后使用构造函数的方法访问该子对象的嵌套对象中的数据。一切正常,直到我深入嵌套对象为止。

我尝试使用各种“var this == that”和“var prop == i”等传递每个变量、对象和属性。我所做的一切似乎都不起作用。

【问题讨论】:

  • foo 没有名为 i 的属性。应该是 this.foo[i]

标签: javascript methods constructor


【解决方案1】:

foo 没有名为 i 的属性。

您希望foo[i] 获取具有该名称的属性。

【讨论】:

  • 这行得通,但我很困惑。为什么foo.hasOwnProperty(i) 返回真?我以为obj.propobj['prop'] 是一样的。
  • 等等...我想我明白了。它实际上是在寻找“foo.i”,而不是“i”代表的变量,因此需要括号表示法来调用变量。感谢您的帮助!
  • @Danneh:是的,但i'i' 不同。
【解决方案2】:

应该是 console.log(this.foo[i])

因为 foo 不包含“i”属性。

【讨论】:

    【解决方案3】:

    您的困惑在于 for-each/for-in 循环通常用于其他编程语言(如 Java、C#)的方式。区别如下:

    // java
    for(int x in list)
        x = x+1;
    
    // javascript
    var x;
    for(x in list)
        list[x] = list[x] + 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 2019-07-28
      • 2014-03-11
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多