hasOwnProperty()、propertyIsEnumerable()和isPrototypeOf()的用法

javascript中有原型这么一个概念,任何一个构造函数都有它对应的原型(prototype),我们可以给这个原型赋予一些我们想要的属性,像下面这样:

function Gadget(name, color){
    this.name = name;
    this.color = color;
    this.whatAreYou = function(){
        return 'I am a ' + this.color + ' ' + this.name;
    }
}

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function(){
    return 'Rating: ' + this.rating + ', price: ' + this.price;
  };


var newtoy = new Gadget('webcam', 'black');

这里我定义了一个Gadget类的实例--newtoy对象。 在这个对象中,我们可以访问对象内部及其原型对象中的属性或者方法。  如果想要获得某个对象所有属性的列表,我们可以使用for-in循环:

for i in newtoy{
    console.log(i + ' = ' + newtoy[i]);
}

我们可以得到下面的结果:

name = webcam
color = black

whatAreYou = function (){
        return 'I am a ' + this.color + ' ' + this.name;
    }

price = 100
rating = 3

getInfo = function (){
    return 'Rating: ' + this.rating + ', price: ' + this.price;
  }

这时候,如果我们想要把原型中的属性过滤掉,就可以首先使用hasOwnProperty()来判断该属性是不是属于对象内部的:

for(var i in newtoy){
    if(newtoy.hasOwnProperty(i))
        console.log(i + ' = ' + newtoy[i]);
}

另外需要注意的几点是:

  • 只有那些可枚举的属性才会被显示出来(一般内建属性都是不可枚举的)
  • 原型中的各个原型属性也会被显示出来,当然前提是它们是可枚举的
  • propertyIsEnumerable()用于测试该属性是否可枚举,对于所以的原型属性,propertyIsEnumerable()都会返回false,包括那些在for-in循环中可枚举的属性。但如果propertyIsEnumerable()的调用是来自原型链上的某个对象,那么该对象中的属性是可枚举的。例如:
    newtoy.constructor.prototype.propertyIsNumerable('price'); 
    //返回: ture

每个对象中都会有一个isPrototypeOf()方法,这个方法会告诉我们当前对象是否是另外一个对象的原型。

var monkey = {
    hair: true,
    feeds: 'bananas'
};

function Human(name){
    this.name = name;
}
Human.prototype = monkey;

var tom = new Human("Tom");
monkey.isPrototypeOf(tom);

//返回: true 

 

 

posted @ 2013-12-10 18:31  CodingMonkey  阅读(881)  评论(1编辑  收藏  举报