考虑一下:
if (someVar.hasOwnProperty('someProperty') ) {
// Do something();
} else {
// Do somethingElse();
}
hasOwnProperty('someProperty')
的正确用法/解释是什么
为什么我们不能简单地使用someVar.someProperty
来检查对象someVar
是否包含名为someProperty
的属性
本例中的属性是什么?
此JavaScript检查什么属性?
发布于 2012-02-22 22:24:36
hasOwnProperty
返回一个布尔值,该值指示在其上调用它的对象是否具有与参数同名的属性。例如:
var x = {
y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
但是,它不会查看对象的原型链。
在使用for...in
构造枚举对象的属性时,使用它非常有用。
如果您想查看完整的细节,ES5 specification一如既往地是一个很好的地方。
发布于 2018-08-17 23:31:31
摘要:
hasOwnProperty()
是一个可以在任何对象上调用的函数,它接受字符串作为输入。它返回一个布尔值,如果属性位于对象上,则返回true
,否则返回false。hasOwnProperty()
位于Object.prototype
上,因此可用于任何对象。
示例:
function Person(name) {
this.name = name;
}
Person.prototype.age = 25;
const willem = new Person('willem');
console.log(willem.name); // Property found on object
console.log(willem.age); // Property found on prototype
console.log(willem.hasOwnProperty('name')); // 'name' is on the object itself
console.log(willem.hasOwnProperty('age')); // 'age' is not on the object itself
在本例中,创建了一个新的Person对象。每个人都有自己的名字,并在构造函数中进行初始化。然而,年龄不是位于对象上,而是位于对象的原型上。因此,对于name,hasOwnProperty()
返回true
,对于age,则返回false
。
实际应用:
当使用for in
循环遍历对象时,hasOwnProperty()
非常有用。如果属性来自对象本身而不是原型,您可以使用它进行检查。例如:
function Person(name, city) {
this.name = name;
this.city = city;
}
Person.prototype.age = 25;
const willem = new Person('Willem', 'Groningen');
for (let trait in willem) {
console.log(trait, willem[trait]); // This loops through all properties, including the prototype
}
console.log('\n');
for (let trait in willem) {
if (willem.hasOwnProperty(trait)) { // This loops only through 'own' properties of the object
console.log(trait, willem[trait]);
}
}
发布于 2012-02-22 22:28:56
hasOwnProperty是一个接受字符串参数的普通JavaScript函数。
在您的示例somevar.hasOwnProperty('someProperty')
中,它检查somevar
函数是否有somepropery
-它返回true和false。
说
function somevar() {
this.someProperty = "Generic";
}
function welcomeMessage()
{
var somevar1 = new somevar();
if(somevar1.hasOwnProperty("name"))
{
alert(somevar1.hasOwnProperty("name")); // It will return true
}
}
https://stackoverflow.com/questions/9396569
复制相似问题