JavaScript 定義類和繼承類的基本步驟

 首先, 是看下JavaScript中創建一個Class的基本步驟, 拿一個例子來說明這個問題:
step 1:
定義Class的構造函數(construct)。
/**
 * Rectangle class definition.
 */
function Rectangle(w, h)
{
    this.width = w;
    this.height = h;
}
小貼士:
var r = new Rectangle(10, 10); js interpreter首先創建一個空的object, 可以想象成一個var r = {}, 然後將新創建的空object作爲call object,調用function Rectangle(w, h)。Js Interpreter 會
爲該函數調用添加一個this來指向當前的call object。 所以構造函數體內就可以爲該call object進行properties的設置, 如this.width = w。

step 2:定義class的instance methods。
每個function都是一個object, 都有一個prototype property。prototype object的properties和methods會被所有的class的instance共享。構造函數Rectangle繼承於他的 prototype, 所以new Rectangle實際時, 是在this上調用Rectangle, 在scope chain上自然也繼承了Rectangle的prototype的對象的屬性。而function的prototype本身也是一個Object instance, 所以自然也繼承了Object的properties和methods。
Rectangle.prototype.area = function () {
    return this.width * this.height;
}

toString是Object的common methods, 如果不定義自己的methods 將基礎Object
Rectangle.prototype.toString = function () {
    return "{" + this.width + ", " + this.height + "}";
}
step 3: 定義Class method和class property。 class method中沒有this,他僅對傳入的參數進行操作。
Rectangle.add = function (a, b)
{
    return new Rectangle(a.width + b.width, a.height + b.height);
}

Rectangle.ZERO_RECT = new Rectangle(0, 0);


對於類繼承的實現。
step1 定義constructor 函數
/**
 * PositionRectangle subclass of Rectangle
 */
function PositionedRectangle (w, h, x, y)
{
    Rectangle.call(this, w, h);//this.superclass(w, h)
    this.x = x;
    this.y = y;
}
小貼士:
構造函數中的Rectangle.call(this, w, h); 在PositionedRectangle中調用父類的構造函數。具體過程如下
var pr = new PositionedRectangle(1, 1, 1, 1);
具體js的interpreter的情況可能如下:
var pr = {};
PositionedRectangle.call(this, 1, 1, 1, 1);
this.x = x;
this.y = y;

Rectangle.call(this, 1, 1);

step 2:修改PositionedRectangle的prototype對象爲Rectangle對象, 這樣, new一個PositionedRectangle 就可以從Rectangle的prototype中繼承properties和methods。
PositionedRectangle.prototype = new Rectangle();
//因爲構造函數中已經通過Rectangle.call(this, w, h)將widht和height properties設置給this了, 所以不再需要Rectangle.prototype的width和height了。
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;

step3: 修改PositionedRectangle的constructor
PositionedRectangle.prototype.constructor = PositionedRectangle;

step4 定義PositionedRectangle的instance method。
PositionedRectangle.prototype.contains = function(x, y)
{
    return (x > this.x && x < this.x + this.width) && (y > this.y && y < this.y + this.width);
}



發佈了31 篇原創文章 · 獲贊 3 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章