1.isPrototypeOf 作用:检测一个对象是否是另一个对象的原型。或者说一个对象是否被包含在另一个对象的原型链中
var p = {x:1};//定义一个原型对象 var o = Object.create(p);//使用这个原型创建一个对象 p.isPrototypeOf(o);//=>true:o继承p var p = {x:1}; Object.prototype.isPrototypeOf(p);//=> true p继承自Object.prototype function Animal(){ this.species = "动物"; }; var eh = new Animal(); Animal.prototype.isPrototypeOf(eh)//=>true总结一下就是: 通过Object.create()创建的对象使用第一个参数作为原型 通过对象直接量的对象使用Object.prototype作为原型 通过new创建的对象使用构造函数的prototype属性作为原型
2.instanceof (用于检测构造函数的prototype属性是否出现在对象的原型链中) 如果左侧对象是右侧类的实例,则表达式返回为true,否则返回false。 object instanceof constructor
3.in hasOwnProperty 属性名 in 对象 (判断某个属性是否存在某个对象中)属性.hasOwnProperty(对象) (判断属性是对象非继承的属性)
例子
function Animal(){}//定义Animal构造函数 Animal.prototype = {//定义Animal原型 species:"动物", say:function(){ console.log('i can say word'); } } function Cat(name,color){//定义构造函数Cat this.name = name; this.color = color; } var F = function(){}; F.prototype = Animal.prototype; Cat.prototype = new F(); Cat.prototype.constructor = Cat;//Cat继承Animal 用F空对象作为媒介 var eh = new Cat('lili','white');//实例化对象 console.log('say' in eh)//=>true console.log('name' in eh)//=>true console.log('color' in eh)//=>true console.log('species' in eh)=>true console.log(eh.hasOwnProperty('say'))=>false 由于say为继承属性 非自有属性 console.log(eh.hasOwnProperty('species'))=>false 由于species为继承属性 非自有属性 console.log(eh.hasOwnProperty('name'))=>true console.log(eh.hasOwnProperty('color'))=>true for(var key in eh){ console.log(key); if(eh.hasOwnProperty(key)){ console.log(key) //=>species say name color } }