目录
一、Reflect.has()
1. 语法
Reflect.has(target, propertyKey)
- target:目标对象。
- propertyKey:属性名,需要检查目标对象是否存在此属性。
2. 示例
let person = {
name:'zs',
age:12,
hobby:['sing','dance'],
height:undefined,
sex:null
}
Reflect.has(person, 'hobby') // true
Reflect.has(person, 'weight') // false
Reflect.has(person, 'valueOf') // true
Reflect.has(person, 'height') // true
Reflect.has(person, 'sex') // true
注:如果该属性存在于原型链中,也会返回 true 。
二、in
1. 语法
target in propertyKey
- target:目标对象。
- propertyKey:属性名,需要检查目标对象是否存在此属性。
2. 示例
let person = {
name:'zs',
age:12,
hobby:['sing','dance'],
height:undefined,
sex:null
}
'hobby' in person // true
'weight' in person // false
'valueOf' in person // true
'height' in person // true
'sex' in person // true
注:如果指定的属性在指定的对象或其原型链中,则 in 运算符 返回 true。可以看出
Reflect.has()方法
和in 运算符
的作用是相同的。
三、Object.prototype.hasOwnPerporty()
1. 语法
obj.hasOwnProperty(prop)
- prop:要检测的属性的 String 字符串形式表示的名称,或者 Symbol。
2. 示例
let person = {
name:'zs',
age:12,
hobby:['sing','dance'],
height:undefined,
sex:null
}
person.hasOwnProperty('hobby') // true
person.hasOwnProperty('weight') // false
person.hasOwnProperty('valueOf') // false
person.hasOwnProperty('height') // true
person.hasOwnProperty('sex') // true
注:这个方法可以用来检测一个对象是否含有特定的自身属性。和 in 运算符不同,该方法会忽略掉那些从原型链上继承到的属性。
当改造一下对象属性,再进行测试。
let person = {
hasOwnProperty: function () {
return false
},
name: 'zs',
age: 12,
hobby: ['sing', 'dance'],
height: undefined,
sex: null,
}
person.hasOwnProperty('hasOwnProperty') // false
person.hasOwnProperty('age') // false
说明:JavaScript 并没有保护 hasOwnProperty 这个属性名。为了避免这一情况,可以使用方法四。
四、Object.prototype.hasOwnProperty.call()
1. 语法
Object.prototype.hasOwnProperty.call(obj,prop)
2. 示例
let person = {
hasOwnProperty:function (){
return false
},
name:'zs',
age:12,
hobby:['sing','dance'],
height:undefined,
sex:null
}
Object.prototype.hasOwnProperty.call(person,'hobby') // true
Object.prototype.hasOwnProperty.call(person,'weight') // false
Object.prototype.hasOwnProperty.call(person,'valueOf') // false
Object.prototype.hasOwnProperty.call(person,'height') // true
Object.prototype.hasOwnProperty.call(person,'sex') // true
Object.prototype.hasOwnProperty.call(person,'hasOwnProperty') // true