How can I bind a property of an object to an anonymous function within the same object?

var foo = {
  x: 1,
  y: (function () {
     return ++this.x;
  })()
};
console.log(foo.y); // undefined rather than 2

      

Let's say that I want to be able to refer to foo.y without using foo.y () . Is it possible?

The above obviously doesn't work, and I'm guessing it's because the closure references are different from this.

+3


source to share


5 answers


If you want to access y as a property, not a function, and return the current value of foo.x to it, the only way I can think of is using getters / setters, which is part of the ES5 spec and is accepted in most modern browsers (but not very useful if you support older browsers).



var foo = {
    x: 1,
    get y() {
        return this.x;
    }
};

      

+6


source


You are not declaring function y as a function, but as a result of a function call. It should be:

var foo = {
  x: 1,
  y: function () {
     return this.x;
  }
};  

      

Or, if you just want to assign y to x:



 var foo = {
    x: 1,
    y: this.x
 };   

      

UPDATE: It is NOT possible to make y synonymous with x. When you declare y it can be a value or a function. It cannot be a reference to another value.

+2


source


Why not just just return x directly if you don't want to use y () as a function? The only reason you are returning a function is because you really need to change the result of x.

var foo = {
     x: 1,
     y: (function () {
          return this.x;
     })()}; 
console.log(foo.x); // 1

      

+1


source


foo.y

is not a function. foo.y

defined as foo.x

.

0


source


var foo = new Object();
foo.x = 1;
foo.y = function() { return this.x; };
console.log(foo.y());

      

or if you are trying to call y

while you are defining foo:

var foo = new Object();
foo.x = 1;
foo.y = x;
console.log(foo.y);

      

0


source







All Articles