2015-07-20 44 views
0
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(); 

我想完成的是使用构造函数来创建子项。这个孩子里面有嵌套的对象,具有不同的属性,我将稍后在我的代码中进行更改。然后使用构造函数的方法访问该子项的嵌套对象内的数据。一切工作,直到我得到两个嵌套的对象深。构造函数方法无法访问for循环中的子对象的嵌套属性

我试着通过各种“var this ==”和“var prop == i”等等来传递每个变量,对象和属性等等。我似乎没有任何工作。

+0

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

回答

1

foo没有任何属性,名称为i

你想要foo[i],以获得该名称的财产。

+0

这工作,但我很困惑。为什么'foo.hasOwnProperty(i)'返回true?我认为'obj.prop'和'obj ['prop']'是一样的。 – Danneh

+0

@丹妮:是的,但“我”与“我”不一样。 – SLaks

+0

等等...我想我明白了。它实际上是寻找“foo.i”,而不是“i”代表的变量,因此需要使用括号表示来调用变量。谢谢你的帮助! – Danneh

0

应当CONSOLE.LOG(this.foo [I])

为Foo DOEN不包含 “i” 的属性。

0

您的困惑在于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;