我正在重写一个 JavaScript 项目,我希望能够使用面向对象的方法来整理当前代码的困惑情况。主要问题是此 JavaScript 应该作为小部件在第 3 方网站内运行,我不能让它与其他网站可能使用的其他 JavaScript 库发生冲突。
所以我正在寻找一种在具有以下要求的 JavaScript 中编写“类类”继承的方法:
- 没有外部库或会与外部库冲突的东西(这排除了从外部库复制和粘贴的可能性)。
- 极简主义 - 我不希望支持代码超过几行代码,也不希望开发人员每次定义新类或方法时都需要大量样板。<
- 应允许动态扩展父对象,以便子对象看到更改(原型(prototype))。
- 应该允许构造函数链接。
- 应该允许
super
类型调用。 - 应该仍然感觉像 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/