Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependency in javascript object

Tags:

javascript

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?

like image 266
Naor Avatar asked Dec 10 '25 14:12

Naor


2 Answers

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;
like image 89
BiAiB Avatar answered Dec 13 '25 04:12

BiAiB


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.

like image 43
Alex Ciminian Avatar answered Dec 13 '25 03:12

Alex Ciminian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!