標籤:屬性 font color follow ret mic var 子類 target
簡單理解:prototype對象是實現物件導向的一個重要機制。每個函數也是一個對象,它們對應的類就是
function,每個函數對象都具有一個子物件prototype。Prototype 表示了該函數的原型,
prototype表示了一個類的屬性的集合。當通過new來產生一個類的對象時,prototype對象的屬
性就會成為執行個體化對象的屬性。 (類似反射出來的一樣)
ps.(在JS 裡面 全都是對象, 類Function是function的頂級超類,function執行個體化了叫對象,在function未執行個體定義的時候,其實這個定義也是屬於Function)
<script>
/*
* 關於prototype,理解這個很有必要
* 可以在類型上使用proptotype來為類型添加行為。這些行為只能在類型的執行個體上體現。
* JS中允許的類型有Array, Boolean, Date, Enumerator, Error, Function, Number, Object, RegExp, String
* 以後這樣分,沒有執行個體化的類稱為類型,執行個體化的類稱為對象執行個體簡稱執行個體
*/
Object.prototype.name = "zhangsan";
Object.prototype.nihao = function(){
alert("i can method name is "+this.name);
}
var obj = new Object();
obj.nihao();
alert(obj.name);
//在執行個體上不能使用prototype,否則會發生編譯錯誤
obj.prototype.sex = "男";//error,無法給一個執行個體prototype
var o = {
name:"zhangsan"
}
o.prototype.age = 30;//error,無法給一個執行個體prototype
//可以為類型定義“靜態”的屬性和方法,直接在類型上調用即可
alert(Object.name);
Object.nihao();
//執行個體不能調用類型的靜態屬性或方法,否則發生對象未定義的錯誤。
Object.class = "三年二班";//類靜態屬性
var ob = new Object();
alert(ob.class); //error 執行個體不能調用類型的靜態屬性和方法
//可以在外部使用prototype為自訂的類型添加屬性和方法。
function Mytest(){
this.name = "zhangsan";
this.age = 20;
}
Mytest.prototype.hello = function(){
alert(this.name);
}
var m = new Mytest();
m.hello();
//在外部不能通過prototype改變自訂類型的屬性或方法。
//該例子可以看到:調用的屬性和方法仍是最初定義的結果。
Mytest.prototype.name = "lisi";
var mm = new Mytest();
alert(mm.name);
//可以在對象執行個體上改變或增加屬性。(這個是肯定的)
//也可以在對象上改變或增加方法。(和普遍的物件導向的概念不同)
mm.name2 = "lisi";
mm.hello = function(){
alert(this.name2);
}
//mm.hello();
//繼承,這個例子說明了一個類型如何從另一個類型繼承。
function Mytest2(){}
Mytest2.prototype = new Mytest;
var m2 = new Mytest2();
alert(m2.name);
//這個例子說明了子類如何重寫父類的屬性或方法。
Mytest2.prototype.name = "wangwu";
Mytest2.prototype.hello = function(){
alert(‘i can mytest2 extend Mytest save method hello‘);
}
var m3 = new Mytest2();
m3.hello();
//子類中的name屬性值不會被父類覆蓋
function Mytest3(){
this.name = "子類中的name屬性值不會被父類覆蓋";
this.age = 20;
}
Mytest3.prototype = new Mytest();
var m4 = new Mytest3();
alert(m4.name);
</script>
js prototype 理解