gpt4 book ai didi

javascript - hasOwnProperty ('getTime' ) 在日期对象上返回 false

转载 作者:行者123 更新时间:2023-11-28 17:40:09 24 4
gpt4 key购买 nike

const test = new Date()
test.hasOwnProperty('getTime') // false
'getTime' in test // true

这意味着 getTime 不在 test 的原型(prototype)中(不是它自己的原型(prototype)),而是在层次结构的更上层(因为 in作品)。为什么会这样,我找不到解释这一点的引用资料。这是由于 getTime“属性”的定义方式所致吗?

最佳答案

hasOwnProperty 不查找原型(prototype)链:

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain. (source)

这就是为什么hasOwnProperty经常被用来检查属性是否存在,在 for...in循环:

for (key in obj) {
if (obj.hasOwnProperty(key))
// do stuff with obj[key]
}
}

关于javascript - hasOwnProperty ('getTime' ) 在日期对象上返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48112458/

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