hasOwnProperty
简介
- 用来过滤 继承自 原型的属性和方法
- 没有保护机制,可能存在一个obj 对象中包含 此名称的属性
- 该属性用来区别属性来自于构造函数还是原型
- 用来判断属性是否来自于对象的自身属性,返回Boolean
var obj = {
hasOwnProperty: function () {},
...
}
demo
避免自定义属性与该属性重名情况
- 尽量使用 hasOwnProperty.call(obj, 函数参数)
知识扩展
- 判断自身属性和继承的属性的方法
- 通过
in
可以判断属性是否是自身属性和继承的属性
var obj = function ()
{
this.name = 'zs'
this.age = 18
}
obj.prototype = {
address: '湖北省'
}
var obj1 = new obj()
console.log('name' in obj1) //output: true
console.log('age' in obj1) //output: true
console.log('zs' in obj1) //output: false
console.log('address' in obj1) //output: true