gpt4 book ai didi

javascript - Javascript 构造函数中属性的点表示法

转载 作者:行者123 更新时间:2023-12-03 04:42:18 25 4
gpt4 key购买 nike

我正在阅读一本教科书,其中一课介绍了定义构造函数时点符号的使用。 (据了解,还有其他语法可用于命名属性。)在尝试类(class)的排列时,结果会引起一些困惑。

以下示例中的一个结果是预期的,但未定义:

function person(){
person.thing = 2;
}

console.log(person.thing);
// outcome: undefined

但是,首先从构造函数创建对象的替代实验会对 person.thing 的值产生意外结果:

function person(){
person.thing = 2;
}

var bob = new person();

console.log(bob.thing);
// outcome: undefined

console.log(person.thing);
// outcome: 2

为什么在从构造函数创建不同名称的对象 bob 后,属性 person.thing 的值现在变为 2?

最佳答案

person 始终引用该函数对象。当您调用 person 函数时,它实际上会运行,以便将该属性放置在对象上。

这与将属性置于任何其他对象上的函数没有什么不同,如下所示:

var myObj = {}
function person() {
myObj.thing = 2
}

console.log("person.thing:", person.thing) // undefined
console.log("myObj.thing:", myObj.thing) // undefined

var bob = new person()

console.log("bob.thing:", bob.thing) // undefined
console.log("person.thing:", person.thing) // undefined
console.log("myObj.thing:", myObj.thing) // 2

所以唯一的区别是,我们现在将 thing 属性添加到 myObj 对象,而不是 person 函数对象。

因此,person 与构造函数创建的对象永远没有任何关系......它构造函数。

<小时/>

在构造函数中,访问正在创建的对象的方法是使用 this 关键字。因此,如果您执行 this.thing = 2,那么 bob.thing 将是 2

关于javascript - Javascript 构造函数中属性的点表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43035212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com