js自定義類,混合的構造函數/原型方式

「混合的構造函數/原型方式」
用構造函數來定義非函數屬性,用原型方式定義對象的函數屬性,結果全部函數都只建立一次,而每一個對象都具備自由的對象屬性實例。
 

 function ocar(color){
  this.color = color;
  this.arr = new Array("s");
 }
 ocar.prototype.showColor = function(){
  alert(this.color);
 }
 var car = new ocar("resd");
 car.showColor();
 
2、爲類添加新方法:
能夠用prototype屬性爲以有的類定義新的方法:
好比爲Array定義一個dequeue()方法
//建立新的方法
Array.prototype.dequeue = function(str){
 this.push(str);
}
var arr = new Array("s");
arr.dequeue("a");
alert(arr.toString());
 
3、重定義已有的方法:
就像給已有類定義新方法同樣,也能夠重寫類的方法。函數名只是指向函數的指針,所以能夠輕易的使用它指向別的函數。從寫已有方法的時候Function的第一個F要大寫
修改本地類toString()方法。
Function.prototype.toString = function(){
 return "重寫toString";
}
function sayHi(){
 alert("Hi");
}
alert(sayHi.toString);
 
4、類的繼承:
JS類的繼承有不少種,這由於JS種的繼承機制並非明確規定的,而是經過模仿實現的,這意味着全部的繼承細節並非徹底解釋程序處理。因此咱們選擇一種適合本身的方法就能夠了。
1、對象冒充:
   構造函數使用this關鍵字給全部屬性和方法賦值,由於構造類只是一種函數,因此可使ClassA的構造函數成爲ClassB的方法,而後調用它,ClassB就會收到ClassA的構造函數中定義的屬性和方法。例如
function oren(name){
 this.name = name;
 this.sayName = function(){
  alert(this.name);
 }
}
function orenB(name,sex){
 this.newfun = oren;
 this.newfun(name);
 delete this.newfun;
 this.sex = sex;
 this.showSex = function(){
  alert(this.sex);
 }
}
var testA = new oren("linan");
testA.sayName();
var testB = new orenB("ln","男");
testB.sayName();
testB.showSex();
全部的新屬性和新方法都必須在刪除了新方法的代碼後定義。不然會覆蓋超類的相關屬性和方法。
 
2、call()方法:
call()方法是與經典的對象冒充方法最類似的方法。它的第一個參數用做this的對象,其餘參都直接傳遞給函數自己。
function oren(name){
 this.name = name;
 this.sayName = function(){
  alert(this.name);
 }
}
function orenB(name,sex){
 oren.call(this,name);
 this.sex = sex;
 this.getSex = function(){
  alert(this.sex);
 }
}
var test = new oren("ln");
test.sayName();
var testB = new orenB("linan","man");
testB.sayName();
testB.getSex();
 

這是call()方法繼承的例子,這裏想讓oren中的關鍵字this等於新建立的orenB對象,所以this是第一個參數函數

相關文章
相關標籤/搜索