测试JavaScript对象上是否存在属性的正确方法是什么? [英] What's the correct way to test for existence of a property on a JavaScript Object?

查看:88
本文介绍了测试JavaScript对象上是否存在属性的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义Javascript对象,我使用 new 创建,并根据创建参数指定属性:

I have a custom Javascript object that I create with new, and assign properties to based on creation arguments:

function MyObject(argument) {
    if (argument) {
        this.prop = "foo";
    }
}
var objWithProp = new MyObject(true); // objWithProp.prop exists
var objWithoutProp = new MyObject(false); // objWithoutProp.prop does not exist

测试<$存在的正确方法是什么c $ c> prop 对象的属性?我已经看到了以下使用的方法,但我不确定这些方法中是否有最好的方式:

What's the correct way to test for the existence of the prop property of the objects? I've seen the following ways used, but I'm not sure if any of these ways is the best way:


  • if(obj.prop){}

  • if(obj.hasOwnProperty(prop)){}

  • if(obj中的prop){}

  • if (obj.prop) {}
  • if (obj.hasOwnProperty("prop")) {}
  • if ("prop" in obj) {}

具体来说,我只对测试是否为此对象明确定义属性感兴趣,而不是在原型链中。此外,该值永远不会设置为 null undefined ,但它可能类似于空对象或阵列。但是,如果你想要包括正确的方法,那么请随意。

Specifically, I'm only interested in testing if the property is explicitly defined for this object, not in the prototype chain. In addition, the value will never be set to null or undefined, but it could be something like an empty object or array. However, if you want to include what the correct way is if those could be the case, feel free.

推荐答案

hasOwnProperty 正好您要查找的内容,因为您指定如果为此对象显式定义属性,而不是在原型链中。每 https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/ Global_Objects / Object / hasOwnProperty ,此方法可用于确定对象是否具有指定属性作为该对象的直接属性;与in运算符不同,此方法不会检查对象的原型链。 - 似乎完全符合您的要求!

hasOwnProperty is exactly what you're looking for, since you specify "if the property is explicitly defined for this object, not in the prototype chain". Per https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty , "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." -- seems to exactly match your requirement!

这篇关于测试JavaScript对象上是否存在属性的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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