Naor
Naor

Reputation: 24103

dependency in javascript object

I have this JavaScript code:

var r = {
    a1:function() {
        alert('hey!');
    },
    a2:this.a1
    /*,
    a3:r.a1, //<--Make an error when running
    a4:a1 //<--Make an error when running
    */ 
};

When executing r.a1() I get an alert but when executing r.a2() I get message:

TypeError: r.a2 is not a function

Why is it? How can I make this work in in one statement?

Upvotes: 3

Views: 138

Answers (2)

Alex Ciminian
Alex Ciminian

Reputation: 11508

If you want to use just the object literal, you can do it like this:

var r = {
    a1:function() {
        alert('hey!');
    },
    a2:function () {
        this.a1();
    }
};

The explanation is: in the object declaration, this refers to your current context - that is, the value of this in the function where you're declaring r.

As BiAiB said, you can't use the name of the object inside the declaration (r in this case), because the variable is not assigned until the object is created.

If you assign a function to a member of the object, when that function gets called, the context will refer to your object, so this will be r.

Upvotes: 2

BiAiB
BiAiB

Reputation: 14132

this, in your definition does not refer to r, but to the actual context (probably window)

you should define it like this:

var r = {
   a1: function() {}
   /* a3: r, // Here r is not yet assigned. First the object is created, then its value
             // is assigned to r.
  */
};

r.a2 = r.a1;
r.a3 = r.a1;

Upvotes: 5

Related Questions