Danneh
Danneh

Reputation: 201

Constructor method can't access nested properties of a child object in a for loop

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();

What I'm trying to accomplish is using a constructor to create a child. The having nested objects inside that child, with various properties that I will change later in my code. Then using a method of the constructor to access data within the nested objects of that child. Everything works until I get two-deep in nested objects.

I've tried passing every variable, object and property around with various "var this == that"s and "var prop == i"s and etc. Nothing I do seems to work.

Upvotes: 0

Views: 97

Answers (3)

himanish.k
himanish.k

Reputation: 117

Your confusion lies in the way that for-each/for-in loops are normally used in other programming languages such as Java, C#. Here's the difference:

// java
for(int x in list)
    x = x+1;

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

Upvotes: 0

jrath
jrath

Reputation: 990

it should be console.log(this.foo[i])

As foo doen not contain "i" property.

Upvotes: 0

SLaks
SLaks

Reputation: 887857

foo has no property named i.

You want foo[i], to get the property with that name.

Upvotes: 1

Related Questions