考虑:
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。
什么是正确的行为?
最佳答案
hasOwnProperty
是一个接受字符串参数的普通 JavaScript 函数。
当您调用 shape1.hasOwnProperty(name)
时,您传递给它的是 name
变量(不存在)的值,就像您写了 alert(name)
。
您需要使用包含 name
的字符串调用 hasOwnProperty
,如下所示:shape1.hasOwnProperty("name")
。
关于javascript - JavaScript 中的 hasOwnProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2600085/