hasOwnProperty在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 }
.welcomeMessage调用body.onload事件。
我期望shape1.hasOwnProperty(name)返回true,但是它返回false。
什么是正确的行为?
hasOwnProperty是一个正常的JavaScript函数,它接受一个string参数。
当你调用shape1.hasOwnProperty(name)你传递的是namevariables的值(不存在),就像你写alert(name) 。
您需要使用包含name的string调用hasOwnProperty ,如下所示: shape1.hasOwnProperty("name") 。
hasOwnProperty期望属性名称为一个string,所以它会是shape1.hasOwnProperty("name")
尝试这个:
函数welcomeMessage()
{
var shape1 = new Shape();
//警报(shape1.draw());
警报(shape1.hasOwnProperty( “名字”));
}
当在JavaScript中使用reflection时,成员对象总是被称为string的名称。 例如:
for(i in obj) { ... }
循环迭代器我将保存一个string值的属性的名称。 要在代码中使用它,必须使用如下的数组运算符来访问属性:
for(i in obj){
alert(“obj的值”+ i +“=”+ obj [i]);
}
我写了一个名为object-hasOwnProperty的开源组件。
例子:
hasOwnProperty({foo: 'bar'}, 'foo') // => true hasOwnProperty({foo: 'bar'}, 'bar') // => false
源代码:
function hasOwnProperty(obj: {}, prop: string|number): boolean { return Object.prototype.hasOwnProperty.call(obj, prop); };
对于variables: –
var lol; console.log(window.hasOwnProperty("lol"));//true console.log("lol" in window);//true
对象: –
var object = { key: "value" }; console.log(object.hasOwnProperty("key"));// true console.log("key" in object);// true console.log(object.key); // undefined