這裡使用rectangle()函數作為例子
1.簡單函數
function rectangle(w,h){
this.width = w;
this.height = h;
}
var test = new rectangle(1,2);建立簡單rectangle對象,包含width,height屬性
額外定義一個計算面積的函數將test對象以參數形式傳入
function getRecArea(rec){
return rec.width * rec.height;
}
console.log( getRecArea(test) );
此時就可以簡單計算任意簡單矩形面積,但上述不符合物件導向編程設計思想,應該將方法也包含進 " 類 "
function rectangle(w,h){
this.width = w;
this.height = h;
this.area = function (){return this.width * this.height}
}
console.log( test.area())
此時已經是一個很友好的解決方案,但還不是最佳化的,每建立一個rectanlge對象的時候變的只是width和height參數,而裡面arec函數在每個rectanlge對象裡面都一樣,這讓我想到java裡面的繼承機制,java裡面繼承自基類,javascript裡面每個對象又有prototype對象屬性(其實在建立對象後就預設初始化了該對象的prototype屬性值,prototype初始化是一個對象並包含一個constructor屬性,這也是每個對象為什麼都有constructor的原因),
添加自prototype裡的函數或屬性都會成為被初始化對象的屬性
function rectangle(w,h){
this.width = w;
this.height = h;
}
rectangle.prototype.arec = function () { return this.width* this .height;} //總結:將不變的屬性放在prototype裡面是很好的解決方案
2.拓展內建類型
不僅使用者自訂的函數有prototype,javascript內建的String ,Date等內建類 也有prototype屬性;
執行個體:判斷字串是否以指定字元結尾
String.prototype.isEndWith = function(c){
return (c == this.charAt(this.length-1))
}
var s = " STRINGc";
console.log(s.isEend());