Javascript:检查对象是否具有属性 [英] Javascript : Check if object has properties

查看:84
本文介绍了Javascript:检查对象是否具有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有几个答案如何检查对象中是否存在属性。

There are several answers here how to check if a property exists in an object.

我一直在使用

if(myObj.hasOwnProperty('propName'))

但我想知道是否存在任何差异

but I wonder if there is any difference from

if('propName' in myObj){


推荐答案

它们几乎相等,区别在于 hasOwnProperty 不检查原型链,而中的确实。

They are almost equal, the difference is that hasOwnProperty does not check down the prototype chain, while in does.

一个例子

var test = function() {}

test.prototype.newProp = function() {}

var instance = new test();

instance.hasOwnProperty('newProp'); // false
'newProp' in instance // true

FIDDLE

如上所述,对象.hasOwnProperty 只返回自己的属性,即直接添加的属性,而不是添加到原型的属性

As noted, Object.hasOwnProperty only returns "own properties", i.e. properties that are added directly, and not properties added to the prototype.

这篇关于Javascript:检查对象是否具有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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