1.instanceof: 判断该对象是否为另一个对象的实例。
该检测会返回一个布尔型(boolean),如果是的话,返回true,否则的话返回false;
function Parent() {
var name = "xiao zhang"
}
function Child() {
var age = 21
}
Child.prototype = new Parent
var child = new Child()
console.log(child instanceof Parent)
console.log(child instanceof Child)
2. isPrototypeOf:判断一个对象象是否为一个实例的原型。
该检测也会返回一个布尔型(boolean),如果是的话,返回true,否则的话返回false;
function Parent() {
var name = "xiao zhang"
}
function Child() {
var age = 21
}
Child.prototype = new Parent
var child = new Child()
var re = Parent.prototype.isPrototypeOf(child)
var re1 = Child.prototype.isPrototypeOf(child)
console.log(re)
console.log(re1)
3.hasOwnProperty:判断对象是否有某个特定的属性,(注意说的是对象的属性,而不是对象原型的属性)必须用字符串指定该属性。
该检测也会返回一个布尔型(boolean),如果对象有某个属性的话,返回true,否则的话返回false;
function Parent() {
this.age = 21
}
function Child() {
this.name = "xiao zhang"
}
Child.prototype = new Parent
var child = new Child()
console.log(child.hasOwnProperty("name"))
console.log(child.hasOwnProperty("age"))
4. propertyIsEnumerable():判断给定的属性是否可以用 for...in 语句进行枚举。
由于 for ... in 枚举是包含原型链上的属性的,但propertyIsEnumerable作用于原型方法上时,始终是返回false的,你可以这么认为,for...in可以枚举对象本身的属性和原型上的属性,而propertyIsEnumerable只能判断本身的属性是否可以枚举。
function Parent() {
this.name = "xiao zhang"
}
function Child() {
this.age = 21
}
Child.prototype = new Parent
var child = new Child()
console.log(child.propertyIsEnumerable("name"))
console.log(child.propertyIsEnumerable("age"))
此外,预定义的属性不是可列举的,而用户定义的属性总是可列举的。所以如果你只想遍历对象本身的属性,可以:
var obj = {
name: "xiao zhang",
age: 21
}
Object.prototype.height = 180
for(var key in obj) {
if (obj.propertyIsEnumerable(key)) {
console.log(key)
}
}