【JavaScript】hasOwnProperty()方法与in操作符

hasOwnProperty()方法

使用 hasOwnProperty()方法(是从 Object 继承来的)可以检测一个属性是存在于实例中,还是存在于原型中。只在给定属性存在于对象实例中时,才会返回 true。

function Person() {}
Person.prototype.name = 'Nicholas'
Person.prototype.age = 29
Person.prototype.job = 'Software Engineer'
Person.prototype.sayName = function () {
  alert(this.name)
}
var person1 = new Person()
var person2 = new Person()
console.log(person1.hasOwnProperty('name')) //false
person1.name = 'Greg'
console.log(person1.name) //"Greg"——来自实例
console.log(person1.hasOwnProperty('name')) //true
console.log(person2.name) //"Nicholas"——来自原型
console.log(person2.hasOwnProperty('name')) //false
delete person1.name
console.log(person1.name) //"Nicholas"——来自原型
console.log(person1.hasOwnProperty('name')) //false

in 操作符

in 操作符:单独使用或者在 for-in 循环中使用。单独使用时,in 操作符会在通过对象能够访问给定属性时返回 true,无论该属性存在于实例中还是原型中。

function Person() {}
Person.prototype.name = 'Nicholas'
Person.prototype.age = 29
Person.prototype.job = 'Software Engineer'
Person.prototype.sayName = function () {
  alert(this.name)
}
var person1 = new Person()
var person2 = new Person()
console.log(person1.hasOwnProperty('name')) //false
console.log('name' in person1) //true
person1.name = 'Greg'
console.log(person1.name) //"Greg" ——来自实例
console.log(person1.hasOwnProperty('name')) //true
console.log('name' in person1) //true
console.log(person2.name) //"Nicholas" ——来自原型
console.log(person2.hasOwnProperty('name')) //false
console.log('name' in person2) //true
delete person1.name
console.log(person1.name) //"Nicholas" ——来自原型
console.log(person1.hasOwnProperty('name')) //false
console.log('name' in person1) //true

不论属性存在于实例中还是存在于原型中,调用"name" in person1 始终都返回 true

posted @ 2020-04-12 11:35  [ABing]  阅读(106)  评论(0编辑  收藏  举报