0
var ok = {
  makeScreens: function () {
    this.screens = {
      x: 2,
      y: this.x * 10;
    };
  }
}

I want to initialize the this.screens variable, but I can't refer to x when I'm initializing y . Can someone tell me, how to refer to the this.screens.x? Thank you very much.

zhy1378
  • 329
  • 1
  • 2
  • 7
  • *this.screens* isn't a variable. *this* is a parameter of an execution context that, in non–strict mode, always references an object. So *this.screens* is a reference to an object property. – RobG Jul 09 '15 at 00:17

2 Answers2

1

You can't. You'll have to do it in two steps:

var ok = {
  makeScreens: function () {
    this.screens = {
      x: 2
    };

    this.screens.y = this.screens.x * 10;
  }
}
-1

Another thing you could do is use a constructor:

var ok = {
  makeScreens: function() {
    this.screens = new (function(){
      this.x = 2;
      this.y = this.x * 10;
    })();
  }
}
xdhmoore
  • 8,935
  • 11
  • 47
  • 90
  • Did you try that? *x* is undefined, and the IIFE returns *undefined* so *new* is going to fail too. – RobG Jul 09 '15 at 00:12
  • my bad. you're right I didn't try it. fixed the x although I'm a little surprised x was undefined. Had to google IIFE. Does this count as an IIFE? The invocation occurs outside of the anonymous function parens, upon `new` i would think. – xdhmoore Jul 09 '15 at 00:31
  • [Please don't do that](http://stackoverflow.com/a/10406585/1048572) – Bergi Jul 09 '15 at 00:48
  • The immediately invoked function expression (IIFE) will be called without setting *this*, so it will default to the global object. So *this.x* is essentially *window.x* in a browser. Not my down vote by the way. – RobG Jul 09 '15 at 04:49
  • @Bergi, thanks for that. I didn't know that was the case. – xdhmoore Jul 09 '15 at 14:26
  • @RobG I am probably doing something wrong but I'm not seeing that behavior when I console.log(this) inside the invoked function. – xdhmoore Jul 09 '15 at 14:26