什么是一个好的简约 Javascript 继承方法?

2023-11-22

我正在重写一个 JavaScript 项目,我希望能够使用面向对象的方法来组织当前代码的混乱。主要担心的是这个 JavaScript 应该作为第 3 方网站内的小部件运行,我不能让它与其他网站可能使用的其他 JavaScript 库发生冲突。

因此,我正在寻找一种在 JavaScript 中编写“类似类”继承的方法,该继承具有以下要求:

  1. 没有外部库或与外部库冲突的东西(阻止从外部库复制和粘贴)。
  2. 简约 - 我不希望支持代码大于几行代码,并且我不希望开发人员每次定义新类或方法时都需要大量样板。
  3. 应允许动态扩展父对象,以便子对象看到更改(原型)。
  4. 应该允许构造函数链接。
  5. 应该允许super类型调用。
  6. 应该还是像 JavaScript 的感觉。

最初我尝试使用简单的原型链:

function Shape(x,y) {
  this.x = x;
  this.y = y;

  this.draw = function() {
    throw new Error("Arbitrary shapes cannot be drawn");
  }
}

function Square(x,y,side) {
  this.x = x;
  this.y = y;
  this.side = side;

  this.draw = function() {
    gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); ...
  }
}
Square.prototype = new Shape();

这解决了需求 1、2 和 6,但 id 不允许超级调用(新函数覆盖父函数),构造函数链接和动态扩展父类不会为子类提供新方法。

任何建议都将受到欢迎。


我建议使用以下模式clone功能从原型而不是实例继承:

function Shape(x, y) {
    this.x = x;
    this.y = y;
}

Shape.prototype.draw = function() {
    throw new Error('Arbitrary shapes cannot be drawn');
};

function Square(x,y,side) {
    Shape.call(this, x, y); // call super constructor
    this.side = side;
}

// inherit from `Shape.prototype` and *not* an actual instance:
Square.prototype = clone(Shape.prototype);

// override `draw()` method
Square.prototype.draw = function() {
    gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); // ...
};

方法驻留在原型中非常重要(出于性能原因,无论如何都应该如此),因此您可以通过以下方式调用超类的方法

SuperClass.prototype.aMethod.call(this, arg1, arg2);

和一些句法糖,你可以让 JS 看起来像一种经典的基于类的语言:

var Shape = Class.extend({
    constructor : function(x, y) {
        this.x = x;
        this.y = y;
    },
    draw : function() {
        throw new Error('Arbitrary shapes cannot be drawn');
    }
});

var Square = Shape.extend({
    constructor : function(x, y, side) {
        Shape.call(this, x, y);
        this.side = side
    },
    draw : function() {
        gotoXY(this.x,this.y); lineTo(this.x+this.side, this.y); // ...
    }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

什么是一个好的简约 Javascript 继承方法? 的相关文章

随机推荐