hasOwnProperty('getTime') 在日期对象上返回 false [英] hasOwnProperty('getTime') returns false on date object

查看:64
本文介绍了hasOwnProperty('getTime') 在日期对象上返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这意味着 getTime 不在 test 的原型中(不是它自己的原型),而是在层次结构的更上层(因为 in作品).为什么会这样,我找不到解释这一点的参考资料.这是因为 getTime属性"是如何定义的?

this means that getTime is not in the prototype of test (not it's own prototype), but further up the hierarchy (because in works). Why is that, I cannot find a reference explaining this. Is this due to how the getTime "property" is defined?

推荐答案

hasOwnProperty 不查找原型链:

每个对象都源自 Object 继承了 hasOwnProperty 方法.该方法可用于确定一个对象是否具有指定的属性作为该对象的直接属性;不像in 运算符,此方法不会检查对象的原型链.(来源)

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 循环:

This is why hasOwnProperty is often used to check if a property exists, in for...in loops:

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

这篇关于hasOwnProperty('getTime') 在日期对象上返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆