Вопрос

I know this is very basic, but why does x return undefined in this code block? Is there a way to define a property and immediately use it to set another property?

    var grid = {
        x : 75,
        y : 75,
        location : [grid.x, grid.y],                
        init : function () {
            console.log(grid.location[0]);
        }
    }
Это было полезно?

Решение

You can't use the variable to access properties of the object before the object has been assigned to the variable. While the object is created, the variable grid is still undefined. While the object is being created, you don't have any reference to it.

You can use the properies once the object has been assigned to the variable:

var grid = {
    x : 75,
    y : 75,
    init : function () {
        console.log(grid.location[0]);
    }
}

grid.location = [grid.x, grid.y];

You can also wrap this in a function expression to get code that returns the complete object:

var grid =
  (function(){

    var obj = {
      x : 75,
      y : 75,
      init : function () {
        console.log(grid.location[0]);
      }
    };
    obj.location = [obj.x, obj.y];

    return obj;

  })();

Другие советы

Is there a way to define a property and immediately use it to set another property?

No. However, you can use a getter, which is more-or-less syntactic sugar for a function:

var grid = {
    x : 75,
    y : 75,
    get location() {
        return [this.x, this.y];
    },                
    init : function () {
        console.log(grid.location[0]);
    }
}

http://jsfiddle.net/mattball/erUJj

This answer sums up the various options: https://stackoverflow.com/a/15486618

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top