object.hasOwnProperty:判断属性是否存在于实例中,存在实例中返回true,例如:
function Student () {
}
Student.prototype.name = "张三"
let student1 = new Student();
console.log(student1.name) // 张三
console.log(student1.hasOwnProperty("name")) // false
student1.name = "李四"
console.log(student1.name) // 李四
console.log(student1.hasOwnProperty("name")) // true
in操作符:能够访问到属性就为true,不管存在于实例还是原型中
function Student () {
}
Student.prototype.name = "张三"
let student1 = new Student();
console.log(student1.name) // 张三
console.log("name" in student1) // true
student1.name = "李四"
console.log(student1.name) // 李四
console.log("name" in student1) // true
利用hasOwnProperty方法和in操作符就可以判断一个属性到底是存在于实例中还是原型中:
function propertyIsInPrototype(object,propertyName) {
return !object.hasOwnProperty(propertyName) && (propertyName in object)
}
function Student () {
}
Student.prototype.name = "张三"
let student1 = new Student();
console.log(student1.name) // 张三
console.log(propertyIsInPrototype(student1,"name")) // true
student1.name = "李四"
console.log(student1.name) // 李四
console.log(propertyIsInPrototype(student1,"name")) // false