整理一下有关原型或者原型链上常出的一些方法

1. istancenof

a instanceof b用来判断a的原型链上是否有b的存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// instanceof
function Father(){
this.sayFather = 'i am father'
}
function Son(){
this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(son instanceof Son) // true
console.log(son instanceof Father) // true
console.log(son instanceof Number) // false
console.log(son instanceof Object) // true
console.log(Father instanceof Object) // true

2. isPrototypeOf

isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Father(){
this.sayFather = 'i am father'
}
function Son(){
this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(Son.isPrototypeOf(son)) // false
console.log(Son.prototype.isPrototypeOf(son)) // true
console.log(Father.prototype.isPrototypeOf(son)) // true
console.log(Number.prototype.isPrototypeOf(son)) // false
console.log(Object.prototype.isPrototypeOf(son)) // true
console.log(Object.prototype.isPrototypeOf(Father)) // true

instanceisPrototypeOf的区别是:instance是比较b.prototype的,而isPrototoyeOf是比较本身

3. getPrototypeOf

Object.getPrototypeOf() 方法返回指定对象的原型(内部[[Prototype]]属性的值)。

1
2
3
4
5
Son.prototype = new Father();
var son = new Son();
console.log(Object.getPrototypeOf(son.__proto__) === Father.prototype ) // true
console.log(Object.getPrototypeOf(son) === Son.prototype) // true
console.log(Object.getPrototypeOf(son) === Father.prototype) // false

4. hasOwnProperty

会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)

1
2
3
4
5
6
7
8
9
10
11
12
function Father(){
this.sayFather = 'i am father'
}
function Son(){
this.saySon = 'i am son'
};
Son.prototype = new Father();
var son = new Son();
console.log(son.saySon) // i am son
console.log(son.sayFather) // i am father
console.log(son.hasOwnProperty('saySon')) // true
console.log(son.hasOwnProperty('sayFather')) // false