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”等等来传递每个变量,对象和属性等等。我似乎没有任何工作。
foo没有名为i的属性。它应该是this.foo [i] – abs