4

If I have this in javascript

var x = {
    "a" : function(q) { return q+1; },
    "b" : function(w) { return (this["a"])(1); } 
};

I want to do something, like access functions from the same object but different properties. For example, in the above code, property a should be fine, but in property b, I want to use the function stored in a. Currently for fun I just have this["a"] which probably doesn't work. But is there a way I can get that function?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474
  • You have my 1001st vote. Congratulations. Wait… no. The user says that I have 871 votes, while the review>badge thing says 1001… Weird. – bjb568 Mar 16 '14 at 06:21

3 Answers3

4

What you have actually works. Have a look at this fiddle here with your object..

Javascript

var x = {
    "a" : function(q) { return q+1; },
    "b" : function(w) { return (this["a"])(1); } 
};

document.body.innerHTML = x.b();

The result from calling x.b() is 2.

More complex objects can do it to like:

var myObj = {
    myFunction: function(testVar)
    {
        return this.Utilities.helperFunction(testVar);
    },
    Utilities: {
        helperFunction: function(anotherVar)
        {
            return anotherVar * 2;
        }
    }
}

You may also notice that in this second example I use a different syntax for getting the property of the object. You can use either this["a"] or this.a which both return the same result. The reason you would use this["a"] is when you want to pass a variable in to grab the property or function.

More information on the this keyword

Turnerj
  • 4,258
  • 5
  • 35
  • 52
0

Just need to print it to the display:

var x = {
        "a" : function(q) {
            return q+1;
        },

        "b" : function(w) {
            return (this.a)(1);
        }
    };

    document.write(x.b(1));
cOp
  • 629
  • 6
  • 7
0

see this awesome overview of this: How does the "this" keyword work?

it goes one level up the chain; inside a function, this is the next level of scope above function, so in the case of x.b=function() {this //}, this looks 1 level up the scope and gets to x.

Community
  • 1
  • 1
chiliNUT
  • 18,989
  • 14
  • 66
  • 106