整理一下有关原型或者原型链上常出的一些方法
1. istancenof
a instanceof b
用来判断a的原型链上是否有b的存在
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 instanceof Son ) console .log (son instanceof Father ) console .log (son instanceof Number ) console .log (son instanceof Object ) console .log (Father instanceof Object )
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)) console .log (Son .prototype .isPrototypeOf (son)) console .log (Father .prototype .isPrototypeOf (son)) console .log (Number .prototype .isPrototypeOf (son)) console .log (Object .prototype .isPrototypeOf (son)) console .log (Object .prototype .isPrototypeOf (Father ))
instance
和isPrototypeOf
的区别是: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 ) console .log (Object .getPrototypeOf (son) === Son .prototype ) console .log (Object .getPrototypeOf (son) === Father .prototype )
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 ) console .log (son.sayFather ) console .log (son.hasOwnProperty ('saySon' )) console .log (son.hasOwnProperty ('sayFather' ))