javascript中有原型这么一个概念,任何一个构造函数都有它对应的原型(prototype),咱们能够给这个原型赋予一些咱们想要的属性,像下面这样:javascript
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循环:java
for i in newtoy{ console.log(i + ' = ' + newtoy[i]); }
咱们能够获得下面的结果:web
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]); }
另外须要注意的几点是:测试
每一个对象中都会有一个isPrototypeOf()方法,这个方法会告诉咱们当前对象是不是另一个对象的原型。this
var monkey = { hair: true, feeds: 'bananas' }; function Human(name){ this.name = name; } Human.prototype = monkey; var tom = new Human("Tom"); monkey.isPrototypeOf(tom);
//返回: true spa