考虑一下:
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。
正确的行为是什么?
发布于 2010-04-08 21:21:05
hasOwnProperty
是一个接受字符串参数的普通JavaScript函数。
当您调用shape1.hasOwnProperty(name)
时,您将向它传递name
变量的值(该变量不存在),就像您编写alert(name)
时一样。
您需要使用包含name
的字符串调用hasOwnProperty
,如下所示:shape1.hasOwnProperty("name")
。
发布于 2010-04-08 21:24:56
hasOwnProperty
希望属性名是字符串,因此它应该是shape1.hasOwnProperty("name")
https://stackoverflow.com/questions/2600085
复制相似问题