为什么用“this.other_property”创建的属性会产生未定义?

时间:2015-06-30 01:37:22

标签: javascript

为什么以下不起作用?根据我读过的所有内容,它看起来应该有效吗?

a = {
  test: "hello",
  test2: this.test
};

我做了console.log(a),我得到test2: undefined

2 个答案:

答案 0 :(得分:1)

在此示例中,this指的是this相对于语句a = ...的值,可能是window(如果您在浏览器中运行此值,如果这是整个代码。)

如果你写了一个构造函数:

var A = function() {
    this.test = "hello";
    this.test2 = this.test;
};

var a = new A();

...... a.test2的价值将是您所期望的。

答案 1 :(得分:0)

由于您的this引用了窗口,并且没有名为test的全局变量/对象,因此window.testundefined