javascript - 什么是好的简约 Javascript 继承方法?

标签 javascript inheritance oop

我正在重写一个 JavaScript 项目,我希望能够使用面向对象的方法来整理当前代码的困惑情况。主要问题是此 JavaScript 应该作为小部件在第 3 方网站内运行,我不能让它与其他网站可能使用的其他 JavaScript 库发生冲突。

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

  1. 没有外部库或会与外部库冲突的东西(这排除了从外部库复制和粘贴的可能性)。
  2. 极简主义 - 我不希望支持代码超过几行代码,也不希望开发人员每次定义新类或方法时都需要大量样板。<
  3. 应允许动态扩展父对象,以便子对象看到更改(原型(prototype))。
  4. 应该允许构造函数链接。
  5. 应该允许super 类型调用。
  6. 应该仍然感觉像 JavaScript。

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

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 不允许 super 调用(新函数覆盖父函数),构造函数链接和动态扩展父类不会向子类提供新方法。

欢迎提出任何建议。

最佳答案

我建议使用 clone function 的以下模式从原型(prototype)而不是实例继承:

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

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

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

与一些 syntactic sugar ,你可以让 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); // ...
    }
});

关于javascript - 什么是好的简约 Javascript 继承方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1404559/

相关文章:

javascript - Firefox 不理解变量包含 ArrayBuffer 而 Chrome 理解

javascript - 有没有办法在 javascript 中隔离 native 对象扩展?

javascript - Knockout 组件 View 在其 ViewModel 可观察更改时不更新

python - 操作来自namedtuple()派生类的属性

C++虚拟运算符删除?

c++ - C++ 基类和派生类之间的继承数据成员

Perl OO 框架和程序设计 - Moose 和 Conway 的由内而外的对象 (Class::Std)

java.lang.IllegalStateException : Could not execute method of the activity , 由 : java. lang.NullPointerException 引起

javascript - var A == var B == 1 寻找 truthy。不工作。是否可以?

javascript - 如何在 motools 中使用 Element Method morph 或 tween 延迟或设置持续时间?