1.in 操作符
in 操作符会在通过对象能够访问给定属性时返回true,无论该属性存在于对象本身还是其原型链上。
1 2 3 4 5 6 7 8 9 10 11 12
| function Person(name) { this.name = name } let obj = new Person('Tom')
Person.prototype.gender = 'male' Person.prototype.code = 23 console.log("name" in obj) console.log('code' in obj) console.log('gender' in obj)
|
2.obj.hasOwnProperty(prop)
hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性。
1 2 3 4 5 6 7 8 9 10
| function Person(name) { this.name = name } let obj = new Person('Tom')
Person.prototype.gender = 'male' Person.prototype.code = 23
console.log(obj.hasOwnProperty('name')) console.log(obj.hasOwnProperty('code'))
|
3.两者结合判断属性位于对象本身还是来自于其原型链
1 2 3 4 5 6 7 8 9 10 11 12 13
| function Person(name) { this.name = name } let obj = new Person('Tom')
Person.prototype.gender = 'male' Person.prototype.code = 23
function propertyFormPrototype(obj, prop) { return !obj.hasOwnProperty(prop) && prop in obj } console.log(propertyFormPrototype(obj, 'name')) console.log(propertyFormPrototype(obj, 'code'))
|