ChrisOdney
ChrisOdney

Reputation: 6384

Javascript weird nested assignment issue in a object literal

I have a JS object property defined in an object literal:

reqHeader: [{name:'Chris'},{age:'06'}]

which I am nesting inside another property in the same object literal:

content: {headers:
              {reqHeader: this.reqHeader}
          },

Now when I try to access this from a method in the same object literal, it says it is undefined:

getHeaders: function(){
    var a = this.content['headers']['reqHeader'];
    alert(a);
}

Full code: http://jsfiddle.net/Amnesiac/zZP83/5/

Thanks, Chris.

Upvotes: 2

Views: 174

Answers (3)

Nicolás Ozimica
Nicolás Ozimica

Reputation: 9748

In your JsFiddle you have:

var obj={

    reqHeader: [{name:'Chris'},{age:'06'}],

    content: {
        headers: {
            reqHeader:this.reqHeader
        }
    },

    getHeaders: function(){
        var a = this.content['headers']['reqHeader'];
        alert(a);
    }
}

obj.getHeaders();

But when you reference this.reqHeader inside the definition of content.headers.reqHeader, the this variable doesn't point to the main object. Indeed, if you chance that line to this:

    content: {
        headers: {
            reqHeader: 'Hello!'
        }
    },

it will work, and will alert the word Hello!.

Upvotes: 1

Pavel Podlipensky
Pavel Podlipensky

Reputation: 8269

@Pointy is right, this in your case means global object, but not the obj object, if you want to have this referred to your obj, you need to make it an instance of some class/function:

var obj= new (function a(){

    this.reqHeader = [{name:'Chris'},{age:'06'}];

    this.content = {headers:{reqHeader:this.reqHeader}

            };

    this.getHeaders = function(){
        var a = this.content['headers']['reqHeader'];
        alert(a);
    };

});

obj.getHeaders();

here is jsfiddle for this

Upvotes: 1

Pointy
Pointy

Reputation: 413682

That won't work, because this is not a reference to that object. That is, it is not the case that JavaScript sets this to refer to an object that's "under construction" inside the object literal block. It remains set to whatever it is outside that expression.

What you can do is something like:

var obj = {
  reqHeaders: /* whatever */,
  content: {
    headers: {
    }
  }
};

obj.content.headers.reqHeader = obj.reqHeader;

Upvotes: 3

Related Questions