Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an object method from an object property definition

Tags:

javascript

I am trying to call an object method from an object (the same object) property definition to no avail.

var objectName = {
     method   :   function() {
          return "boop";
     },
     property :   this.method()
};

In this example I want to assign the return value of objectName.method ("boop") to objectName.property.

I have tried objectName.method(), method(), window.objectName.method(), along with the bracket notation variants of all those as well, ex. this["method"], with no luck.

like image 674
Ian Avatar asked Jan 01 '11 23:01

Ian


Video Answer


2 Answers

At initialization this does not refer to the object holding the property method (which is not yet initialized) but to the curent context - and since this has no method property you will get a TypeError.

If it is a custom getter you want, then you might look into using getters and setters in javascript - they are not supported by ECMAscript prior to ES5, but many engines support them nonetheless.

like image 181
Sean Kinsey Avatar answered Oct 13 '22 11:10

Sean Kinsey


I can see no reason why you would want to do this?

Why not just use a getter, if you don't want to use the method name.

var objectName = {
   method   :   function() {
        return "boop";
   },
   property :   function () {
        return this.method();
   }
};
like image 40
Mads Mogenshøj Avatar answered Oct 13 '22 09:10

Mads Mogenshøj