首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript中hasOwnProperty中的属性是什么?

JavaScript中hasOwnProperty中的属性是什么?
EN

Stack Overflow用户
提问于 2012-02-22 22:19:05
回答 4查看 202.1K关注 0票数 114

考虑一下:

代码语言:javascript
复制
if (someVar.hasOwnProperty('someProperty') ) {
 // Do something();
} else {
 // Do somethingElse();
}

hasOwnProperty('someProperty')的正确用法/解释是什么

为什么我们不能简单地使用someVar.someProperty来检查对象someVar是否包含名为someProperty的属性

本例中的属性是什么?

此JavaScript检查什么属性?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-02-22 22:24:36

hasOwnProperty返回一个布尔值,该值指示在其上调用它的对象是否具有与参数同名的属性。例如:

代码语言:javascript
复制
var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

但是,它不会查看对象的原型链。

在使用for...in构造枚举对象的属性时,使用它非常有用。

如果您想查看完整的细节,ES5 specification一如既往地是一个很好的地方。

票数 191
EN

Stack Overflow用户

发布于 2018-08-17 23:31:31

摘要:

hasOwnProperty()是一个可以在任何对象上调用的函数,它接受字符串作为输入。它返回一个布尔值,如果属性位于对象上,则返回true,否则返回false。hasOwnProperty()位于Object.prototype上,因此可用于任何对象。

示例:

代码语言:javascript
复制
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()非常有用。如果属性来自对象本身而不是原型,您可以使用它进行检查。例如:

代码语言:javascript
复制
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]);
  }
}

票数 14
EN

Stack Overflow用户

发布于 2012-02-22 22:28:56

hasOwnProperty是一个接受字符串参数的普通JavaScript函数。

在您的示例somevar.hasOwnProperty('someProperty')中,它检查somevar函数是否有somepropery -它返回true和false。

代码语言:javascript
复制
function somevar() {
    this.someProperty = "Generic";
}

function welcomeMessage()
{
    var somevar1 = new somevar();
    if(somevar1.hasOwnProperty("name"))
    {
        alert(somevar1.hasOwnProperty("name")); // It will return true
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9396569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档