在javascript中的hasOwnProperty

Thi*_*n S 73 javascript

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
}
Run Code Online (Sandbox Code Playgroud)

.welcomeMessage呼吁这个body.onload事件.

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

什么是正确的行为?

SLa*_*aks 151

hasOwnProperty 是一个普通的Javascript函数,它接受一个字符串参数.

当你调用时,shape1.hasOwnProperty(name)你传递的是name变量的值(它不存在),就像你写的那样alert(name).

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


Pab*_*era 18

hasOwnProperty 期望属性名称为字符串,因此它将是 shape1.hasOwnProperty("name")