Javascript方法小札記
來源:程序員人生 發布時間:2015-04-13 08:22:35 閱讀次數:4140次
1靜態方法
存儲在運行內存上的靜態區域,該類方法由JS體系內類所持有。
-
var BaseClass = new Function;
-
var Class2 = BaseClass;
-
BaseClass.f1 = function(){
-
alert("BaseClass ' s static method");
-
}
-
Class2.f2 = function(){
-
alert("Class2 ' s static method");
-
}
-
BaseClass.f1();
-
BaseClass.f2();
-
Class2.f1();
-
Class2.f2();
2對象方法
對象方法即創建對象時,以屬性的方式創建的方法,同時加入了該對象的原型鏈中。
3原型方法
1般用于既存的對象,擴大該對象或擴大繼承該對象的對象。將方法動態的添加到對象的原型鏈中。
-
var BaseClass = function() {
-
this.method1 = function(){
-
alert(' Defined by the "this" in the instance method');
-
}
-
};
-
var instance1 = new BaseClass();
-
instance1.method1 = function(){
-
alert(' Defined directly in the instance method');
-
}
-
BaseClass.prototype.method1 = function(){
-
alert(' Defined by the prototype instance method ');
-
}
-
instance1.method1();
通過運行結果跟蹤測試可以看出直接定義在實例上的變量的優先級要高于定義在“this”上的,而定義在“this”上的又高于 prototype定義的變量。即直接定義在實例上的變量會覆蓋定義在“this”上和prototype定義的變量,定義在“this”上的會覆蓋prototype定義的變量。
根據運行測試,可以判斷,對象方法創建時,是將方法加入原型鏈堆棧的最上層,而實例對象中,原型的調用又相對本身對象方法處于底層。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈