什么是原型
原型是一個對象咸这,其他對象可以通過它實(shí)現(xiàn)屬性繼承。所有的對象都擁有原型魔眨,所有的對象都可以成為原型媳维。
獲得原型的方法:
var a = {};
//Firefox 3.6 and Chrome 5
Object.getPrototypeOf(a); //[object Object]
//Firefox 3.6, Chrome 5 and Safari 4
a.__proto__; //[object Object]
//all browsers
a.constructor.prototype; //[object Object]
注意,當(dāng)你試圖獲取一個主數(shù)據(jù)類型的原型時(shí)冰沙,它被強(qiáng)制轉(zhuǎn)化成了一個對象:
//(works in IE too, but only by accident)
false.__proto__ === Boolean(false).__proto__; //true
原型與原型屬性
原型例子:
//創(chuàng)建一個函數(shù)bvar b = function(){ var one; }
//使用b創(chuàng)建一個對象實(shí)例cvar c = new b();
//查看b 和c的構(gòu)造函數(shù)
b.constructor; // function Function() { [native code]}
b.constructor==Function.constructor; //true
c.constructor; //實(shí)例c的構(gòu)造函數(shù) 即 b function(){ var one; }c.constructor==b //true
//b是一個函數(shù)侨艾,查看b的原型如下b.constructor.prototype // function (){}b.__proto__ //function (){}
//b是一個函數(shù)执虹,由于javascript沒有在構(gòu)造函數(shù)constructor和函數(shù)function之間做區(qū)分拓挥,所以函數(shù)像constructor一樣,//有一個原型屬性恕曲,這和函數(shù)的原型(b.__proto__ 或者b.construtor.prototype)是不一樣的b.prototype //[object Object] 函數(shù)b的原型屬性
b.prototype==b.constructor.prototype //fasleb.prototype==b.__proto__ //falseb.__proto__==b.constructor.prototype //true
//c是一個由b創(chuàng)建的對象實(shí)例嫂侍,查看c的原型如下c.constructor.prototype //[object Object] 這是對象的原型c.__proto__ //[object Object] 這是對象的原型
c.constructor.prototype==b.constructor.prototype; //false c的原型和b的原型比較c.constructor.prototype==b.prototype; //true c的原型和b的原型屬性比較
//為函數(shù)b的原型屬性添加一個屬性max
b.prototype.max = 3
//實(shí)例c也有了一個屬性max
c.max //3
上面的例子中预伺,對象實(shí)例c的原型和函數(shù)的b的原型屬性是一樣的,如果改變b的原型屬性盖灸,則對象實(shí)例c的原型也會改變。
理解一個函數(shù)的原型屬性(function’s prototype property )其實(shí)和實(shí)際的原型(prototype)沒有關(guān)系對我們來說至關(guān)重要磺芭。如實(shí)例對象a的原型(a.proto)是對函數(shù)A的原型屬性(A.prototype)的引用:
var A = function(name){this.name = name;}
var a = new A(‘a(chǎn)lpha’);a.name; //’alpha’
A.__proto__.max = 19880716;
a.max //undefined
原型可以做什么
String.prototype.times = function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
}
"hello!".times(3); //"hello!hello!hello!";
"please...".times(6);//"please...please...please...please...please...please..."
注意事項(xiàng)
hasOwnProperty在for-in中一般用來檢測是否為自身屬性赁炎,也是JavaScript中唯一一個不會遍歷原型鏈的方法。但是這方法有可能被覆蓋改寫:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // 總是返回 false
// 使用{}對象的 hasOwnProperty徙垫,并將其上下為設(shè)置為foo
{}.hasOwnProperty.call(foo, 'bar'); // true