所以假设我们有一个对象foo,其中有2个变量,一个是另一个字符串。例如:
foo = {price:20,string:"bar "+this.price}
当我这样做时,调用console.log(foo.string)给我
bar undefined
但如果我这样做:
foo = {price:20,string:"bar "+this.price}
foo = {price:20,string:"bar "+foo.price}
它按预期工作(显然),原因是什么。不工作?
答案 0 :(得分:2)
this
这里不是您的想法。它位于全局范围内,因此它是对window
对象的引用,而不是对您正在创建的对象的引用。
这是一个证据:
foo = {price:20,string:"bar "+this}
console.log(foo);

由于window
对象没有名为price
的属性,因此widnow.price
为undefined
。
当你这样做时:
foo = {price:20,string:"bar "+this.price}
foo = {price:20,string:"bar "+foo.price}
第一行将foo
定义为{price:20,string:"bar undefined"}
,然后在第二行中我们已将foo
的{{1}}属性设置为20,所以第二行结果price
设置为foo
。
答案 1 :(得分:1)
如果要对对象使用this
,则应使用构造函数来创建对象。
function Foo(price) {
this.price = price; // <-- now this will refer to this function scope when used with `new` keyword
this.string = 'bar' + this.price;
}
a = new Foo(12);
a.price; // 12
a.string; // 'bar12'
您的代码有效,因为:
foo = {price:20,string:"bar "+this.price} // <-- foo was declared here
foo = {price:20,string:"bar "+foo.price} // <-- foo is available here
答案 2 :(得分:0)
undefined
来自window.price
undefined
,this
,window
,在全球范围内,是指console.log
,正如您在第一个中看到的那样console.log(`this === window = ${ this === window }`);
foo = { price:20, string: "bar " + this.price };
console.log(foo);
此处:
foo
&#13;
第二种情况仅适用,因为在第一个语句中,您将已经定义foo
,因此当您执行下一个语句时,您将使用foo.price
重新定义20
先前定义的,foo = { price:20, string: "bar " + this.price };
console.log("FIRST TIME =", foo);
console.log("Now foo.price =", foo.price);
foo = { price:20, string: "bar " + foo.price };
console.log("SECOND TIME =", foo);
:
foo
&#13;
如果您只执行第二个语句,则会抛出错误,因为foo = { price:20, string: "bar " + foo.price };
无法定义:
&
&#13;