【发布时间】: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