简体   繁体   English

Javascript +基本对象文字范围问题

[英]Javascript + Basic Object Literal Scope Issue

I know this is very basic, but why does x return undefined in this code block? 我知道这是非常基本的,但是为什么x在此代码块中返回undefined? 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. 创建对象时,变量grid仍未定义。 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: 不,但是,您可以使用getter ,它对于某种功能来说或多或少是语法糖:

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 http://jsfiddle.net/mattball/erUJj

This answer sums up the various options: https://stackoverflow.com/a/15486618 该答案总结了各种选项: https : //stackoverflow.com/a/15486618

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM