一起加入同一个对象(未捕获的ReferenceError)内的两个字符串属性

一起加入同一个对象(未捕获的ReferenceError)内的两个字符串属性

问题描述:

比方说,我有这样的:一起加入同一个对象(未捕获的ReferenceError)内的两个字符串属性

var test = { 
 
    hello: "one", 
 
    world: "two", 
 
    all: hello + world 
 
} 
 

 
$('h1').text("Test > all: " + test.all);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1></h1> 
 
<h2>Test</h2>

为什么会当它明显高于定义了以下错误?

Uncaught ReferenceError: hello is not defined

我试过添加this但没有运气。

+2

这是因为在调用'hello'和'world'来设置'all'属性的时候,对象还不存在。 –

您的错误是因为您尝试从未定义的变量中设置“全部”。使用你尝试做一个getter:

var test = { 
    hello: "one", 
    world: "two", 
    get all() { return this.hello + this.world; } 
} 

$('h1').text("Test > all: " + test.all); 
+2

这是ES6语法。 –

+1

@HamletHakobyan,没有ecma-262 5.1 –

+1

@HamletHakobyan,除非你运行IE8和+2年前的浏览器,这是一个兼容的实现(参见[MDN](https://developer.mozilla.org/en-US/docs)/Web/JavaScript/Reference/Functions/get)) –

这是因为对象并不在点尚不存在,通话双方helloworld设置all属性。如果您需要此行为,使得它执行定义all为函数的对象已经被定义后:

var test = { 
 
    hello: "one", 
 
    world: "two", 
 
    all: function() { 
 
     return this.hello + this.world 
 
    } 
 
} 
 

 
$('h1').text("Test > all: " + test.all());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1></h1> 
 
<h2>Test</h2>

你也可以做的两个步骤:

var test = { 
    hello: "one", 
    world: "two" 
} 

test.all = test.hello + test.world;