“混合的構造函數/原型方式”
用構造函數來定義非函數屬性,用原型方式定義對象的函數屬性,結果所有函數都只創建一次,而每個對象都具有自由的對象屬性實例。
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();
二、為類添加新方法:
可以用prototype屬性為以有的類定義新的方法:
比如為Array定義一個dequeue()方法
//創建新的方法
Array.prototype.dequeue = function(str){
this.push(str);
}
var arr = new Array("s");
arr.dequeue("a");
alert(arr.toString());
this.push(str);
}
var arr = new Array("s");
arr.dequeue("a");
alert(arr.toString());
三、重定義已有的方法:
就像給已有類定義新方法一樣,也可以重寫類的方法。函數名只是指向函數的指針,因此可以輕易的使用它指向別的函數。從寫已有方法的時候Function的第一個F要大寫
修改本地類toString()方法。
Function.prototype.toString = function(){
return "重寫toString";
}
function sayHi(){
alert("Hi");
}
alert(sayHi.toString);
return "重寫toString";
}
function sayHi(){
alert("Hi");
}
alert(sayHi.toString);
四、類的繼承:
JS類的繼承有很多種,這因為JS種的繼承機制並不是明確規定的,而是通過模仿實現的,這意味着所有的繼承細節並不是完全解釋程序處理。所以我們選擇一種適合自己的方法就可以了。
一、對象冒充:
構造函數使用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();
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();
所有的新屬性和新方法都必須在刪除了新方法的代碼后定義。否則會覆蓋超類的相關屬性和方法。
二、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();
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是第一個參數