JavaScript面向對象編程(3)prototype簡介
來源:程序員人生 發布時間:2014-12-07 09:32:17 閱讀次數:3218次
prototype――原型,用于給對象動態地新增屬性和行動
先定義個構造函數
//小配件
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return '我是 ' + this.color + '的' + this.name;
}
this.get = function(what){
return this[what];//對象與數組有類似的地方,js的[]中可以是下標,也能夠是對象的屬性
}
}
使用prototype增加屬性和方法
/*使用prototype增加屬性和方法*/
Gadget.prototype.price = 100;//增加屬性
Gadget.prototype.rating = 3;
//增加行動==方法==或叫函數
Gadget.prototype.getInfo = function() {
return '等級: ' + this.rating + ', 價格: ' + this.price;
};
/*也可批量替換或新增*/
Gadget.prototype = {
price:100,
rating:3,
getInfo:function() {
//可訪問原始屬性
<span style="white-space:pre"> </span>return '名字:'+this.name+',等級: ' + this.rating + ', 價格: ' + this.price;
}
};
var toy = new Gadget('網絡攝像頭','黑色');
alert(toy.getInfo());//可訪問新的方法,也可訪問原本的屬性和方法
/*屬性的遍歷及判斷*/
for(i in toy){
if(typeof(toy[i])!="function")
//遍歷出toy上可以訪問的所有的屬性及屬性值
alert(i + '=' + toy[i]);
}
//判斷屬性是否是原始的
for(prop in toy){
<span style="white-space:pre"> </span>if (toy.hasOwnProperty(prop)) {
<span style="white-space:pre"> </span>alert("原始:"+prop + '=' + toy[prop]);
<span style="white-space:pre"> </span>}
}
每一個對象都有isPrototypeOf方法,用于判斷當前對象是否是另外1個對象的prototype
/*Every object also gets the isPrototypeOf() method.
* This method tells you whether that specific object is used as a prototype of another object.
每一個對象都有isPrototypeOf方法,用于判斷當前對象是否是另外1個對象的prototype
* */
var monkey = {
hair: true,
feeds: 'bananas',
breathes: 'air'
};
function Human(name) {
this.name = name;
}
Human.prototype = monkey;
var george = new Human('George');
alert("monkey.isPrototypeOf(george)==="+ monkey.isPrototypeOf(george));
總結:
可以將prototype看作是1個額外的對象,在構造器上援用1個prototype對象,這個對象具有1些屬性和方法;
通過構造函數產生的對象也自然鏈接了這個prototype對象,而且可以把prototype對象的屬性和方法當作自己的;
固然,原始的屬性和通過prototype取得的屬性還是有些不1樣,最少通過hasOwnProperty可以判斷出這個屬性是否是自己的原生屬性;
另外,可以通過a.isPrototypeOf(b)來判斷a是否是b的prototype。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈