目录
目录
检测属性:
检测一个属性是否属于某个对象。常用的方式主要有3种:
in
hasOwnProperty()
propertyIsEnumerable()
instanceof
in (不是原型方法)
检测某属性是否是某对象的自有属性或者是继承属性
var obj = {
name: 'zhangsan',
age: 18,
school: 'xx大学'
}
//in运算符的左侧为属性名称,右侧为对象
console.log('name' in obj); //true
console.log('age' in obj); //true
console.log('gender' in obj); //false
//如果用in判断一个属性存在,这个属性不一定是obj的,它可能是obj继承得到的,如:
'toString' in obj; // true
因为toString定义在object对象中,而所有对象最终都会在原型链上指向object,所以obj也拥有toString属性。
Object.prototype.hasOwnProperty()
检测给定的属性是否是对象的自有属性,对于继承属性将返回false
var obj = {
name: 'zhangsan',
age: 18,
school: 'xx大学'
}
console.log(obj.hasOwnProperty('name')); //true
console.log(obj.hasOwnProperty('age')); //true
console.log(obj.hasOwnProperty('toString')); //false,toString为继承属性
console.log(obj.hasOwnProperty('gender')); //false
Object.prototype.propertyIsEnumerable()
propertyIsEnumerable()是hasOwnProperty()的增强版,除了是自身属性外,还要求是可枚举(可删除的)属性,即我们创建的属性。
var obj = {
name: 'zhangsan',
age: 18,
school: 'xx大学'
}
console.log(obj.propertyIsEnumerable('name')); //true
console.log(obj.propertyIsEnumerable('age')); //true
console.log(obj.propertyIsEnumerable('toString')); //false,不可枚举
console.log(obj.propertyIsEnumerable('gender')); //false
instanceof
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。或者说判断一个对象是某个对象的实例。
// 自定义构造函数
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.sayName = function () {
console.log(this.name);
}
}
var person1 = new Person('zhangsan', 29, 'male');
var person2 = new Person('lisi', 19, 'female');
person1.sayName(); // zhangsan
person2.sayName(); // lisi
//instanceof 操作符的结果所示:
console.log(person1 instanceof Object); // true
console.log(person1 instanceof Person); // true
console.log(person2 instanceof Object); // true
console.log(person2 instanceof Person); // true