this.x = undefined,但是objName.x有效吗?

时间:2018-01-31 02:12:16

标签: javascript object

所以假设我们有一个对象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}

它按预期工作(显然),原因是什么。不工作?

3 个答案:

答案 0 :(得分:2)

this这里不是您的想法。它位于全局范围内,因此它是对window对象的引用,而不是对您正在创建的对象的引用。

这是一个证据:



foo = {price:20,string:"bar "+this}

console.log(foo);




由于window对象没有名为price的属性,因此widnow.priceundefined

当你这样做时:

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

参考:https://www.w3schools.com/js/js_object_constructors.asp

答案 2 :(得分:0)

undefined来自window.price undefinedthiswindow,在全球范围内,是指console.log,正如您在第一个中看到的那样console.log(`this === window = ${ this === window }`); foo = { price:20, string: "bar " + this.price }; console.log(foo);此处:

&#13;
&#13;
foo
&#13;
&#13;
&#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);

&#13;
&#13;
foo
&#13;
&#13;
&#13;

如果您只执行第二个语句,则会抛出错误,因为foo = { price:20, string: "bar " + foo.price };无法定义:

&#13;
&#13;
&
&#13;
&#13;
&#13;