gpt4 book ai didi

javascript hasOwnProperty 返回 true 而不是 false?

转载 作者:行者123 更新时间:2023-11-30 09:46:22 24 4
gpt4 key购买 nike

我不明白为什么要 alert(John.hasOwnProperty('firstName'));返回 true 而 firstName 是在 Person 原型(prototype)中定义的,而不是在实例 John 中定义的?

https://jsfiddle.net/xfdnsg2w/

  Person = function(firstName, lastName) {

this.firstName = firstName;
this.lastName = lastName;

}

var John = new Person("John");
alert(John.hasOwnProperty('toString'));
alert(John.hasOwnProperty('firstName'));

最佳答案

代码中的“firstName”属性在 Person 原型(prototype)中定义。它在构造函数中被初始化为“自己的”属性。

即使原型(prototype)上有“firstName”和“lastName”属性,只要您在构造函数中为它们赋值,它们就会变成“自己的”属性。原型(prototype)属性一般作为属性来访问,通常它们有函数作为值。

关于javascript hasOwnProperty 返回 true 而不是 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772974/

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