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);
}

原文地址:https://www.cnblogs.com/yuboyue/p/2109874.html