prototype 是javascript實(shí)現(xiàn)繼承的基本方法,但這種繼承和java等繼承有什么本質(zhì)的區(qū)別呢
在 JavaScript 中,對象的 prototype 在運(yùn)行期是不可見的,只能在定義對象的構(gòu)造函數(shù)時(shí),創(chuàng)建對象之前設(shè)定。下面的用法都是錯誤的:
o2.prototype?
=
?o1;
/* *
??這時(shí)只定義了?o2?的一個(gè)名為“prototype”的屬性,
??并沒有將?o1?設(shè)為?o2?的?prototype。
*/
?
// ?---------------
?
f2? = ? function (){};
o2? = ? new ?f2;
f2.prototype? = ?o1;
/* *
??這時(shí)?o1?并沒有成為?o2?的?prototype,
??因?yàn)?o2?在?f2?設(shè)定?prototype?之前已經(jīng)被創(chuàng)建。
*/
?
// ?---------------
?
f1? = ? function (){};
f2? = ? function (){};
o1? = ? new ?f1;
f2.prototype? = ?o1;
o2? = ? new ?f2;
/* *
??同樣,這時(shí)?o1?并不是?o2?的?prototype,
??因?yàn)?JavaScript?不允許構(gòu)造函數(shù)的?prototype?對象被其它變量直接引用。
*/
/* *
??這時(shí)只定義了?o2?的一個(gè)名為“prototype”的屬性,
??并沒有將?o1?設(shè)為?o2?的?prototype。
*/
?
// ?---------------
?
f2? = ? function (){};
o2? = ? new ?f2;
f2.prototype? = ?o1;
/* *
??這時(shí)?o1?并沒有成為?o2?的?prototype,
??因?yàn)?o2?在?f2?設(shè)定?prototype?之前已經(jīng)被創(chuàng)建。
*/
?
// ?---------------
?
f1? = ? function (){};
f2? = ? function (){};
o1? = ? new ?f1;
f2.prototype? = ?o1;
o2? = ? new ?f2;
/* *
??同樣,這時(shí)?o1?并不是?o2?的?prototype,
??因?yàn)?JavaScript?不允許構(gòu)造函數(shù)的?prototype?對象被其它變量直接引用。
*/
從上面的例子可以看出:如果你想讓構(gòu)造函數(shù) F2 繼承另外一個(gè)構(gòu)造函數(shù) F1 所定義的屬性和方法,那么你必須先創(chuàng)建一個(gè) F1 的實(shí)例對象,并立刻將其設(shè)為 F2 的 prototype。筆者認(rèn)為這種繼承方法不夠直觀,并且將對象的設(shè)計(jì)期和運(yùn)行期混在一起。
就是拿類來“繼承”另外一個(gè)類的實(shí)例的說。。。
繼續(xù):
function
?MyObject1(formalParameter){
???? this .testNumber? = ?formalParameter;
}
function ?MyObject2(formalParameter){
???? this .testString? = ?formalParameter;
}
MyObject2.prototype? = ? new ?MyObject1(? 8 ?);
var ?objectRef? = ? new ?MyObject2(? " String_Value " ?);
???? this .testNumber? = ?formalParameter;
}
function ?MyObject2(formalParameter){
???? this .testString? = ?formalParameter;
}
MyObject2.prototype? = ? new ?MyObject1(? 8 ?);
var ?objectRef? = ? new ?MyObject2(? " String_Value " ?);
Theinstance of
MyObject2
referred to by the objectRef
variable has a prototype chain. The first object in that chain is the instance of MyObject1
that was created and assigned to the prototype property of the MyObject2
constructor. The instance of MyObject1
has a prototype, the default Object prototype that corresponds with the object referred to by Object.prototype
. Object.prototype
has a null prototype(!) so the prototype chain comes to an end at this point. 說明prototype是類的一個(gè)屬性而不是實(shí)例的屬性。。。
prototype是一個(gè)鏈,鏈的盡頭是Object.prototype而這個(gè)prototype有一些toString()之類的通用方法,且這個(gè)prototype的prototype為null
現(xiàn)在了解了怎樣通過prototype實(shí)現(xiàn)繼承了吧:
1,如果給一個(gè)實(shí)例動態(tài)添加屬性的話,這個(gè)屬性只能做用于這個(gè)實(shí)例
2,如果給一個(gè)類的prototype添加屬性的話,這個(gè)屬性會在類的每個(gè)實(shí)例中產(chǎn)生一個(gè)拷貝,即會做用于類的所有實(shí)例,產(chǎn)生類似繼承的效果