JavaScript中的hasOwnProperty


79

考虑:

function Shape() {
    this.name = "Generic";
    this.draw = function() {
        return "Drawing " + this.name + " Shape";
    };
}

function welcomeMessage()
{
    var shape1 = new Shape();
    //alert(shape1.draw());
    alert(shape1.hasOwnProperty(name));  // This is returning false
}

.welcomeMessage呼吁body.onload事件。

我期望shape1.hasOwnProperty(name)返回true,但是返回false。

正确的行为是什么?


5
它需要一个字符串,"name"而不是name
AO_

Answers:


157

hasOwnProperty 是一个带有字符串参数的普通JavaScript函数。

调用shape1.hasOwnProperty(name)时将其传递给name变量的值(该变量不存在),就像编写一样alert(name)

您需要hasOwnProperty使用包含的字符串进行调用name,如下所示:shape1.hasOwnProperty("name")


1
不要忘了添加hasOwnProperty()返回一个布尔值,该布尔值指示指定的属性(在这种情况下为名称)是否存在
maheshmnj


3

试试这个:

函数welcomeMessage()
{
    var shape1 = new Shape();
    // alert(shape1.draw());
    alert(shape1.hasOwnProperty(“ name”));
}

在JavaScript中使用反射时,成员对象始终被称为字符串名称。例如:

for(i in obj) { ... }

循环迭代器i将包含带有属性名称的字符串值。要在代码中使用它,您必须使用数组运算符来寻址属性,如下所示:

 for(i in obj){
   alert(“ obj的值。” + i +“ =” + obj [i]);
 }

2

hasOwnProperty()是用于验证对象键的不错的属性。 例:

var obj = {a:1, b:2};

obj.hasOwnProperty('a') // true

关于“好的财产”:这是一个功能吗?
Peter Mortensen
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.