如何在 javascript 中实现特征?
SO是一场狗屎秀。感谢您的搭车。
有不同的方法,同时也有生产就绪的库。
Mixin 是跨类层次结构的代码重用的最古老的形式。它们需要按线性顺序组合,因为 Mixin 的概念不涵盖/识别冲突解决功能。
特征是细粒度的代码重用单元,也适用于类级别;但它们更灵活,因为 Traits 必须提供用于组合、排除或别名方法的组合运算符。
我确实建议阅读两篇论文,它们都涵盖了与库无关的基于纯函数的 Mixins / Traits / Talents 方法。
var Enumerable_first = function () {
this.first = function () {
return this[0];
};
};
var list = ["foo", "bar", "baz"];
console.log("(typeof list.first)", (typeof list.first)); // "undefined"
Enumerable_first.call(list); // explicit delegation
console.log("list.first()", list.first()); // "foo"
...第一个示例作用于“实例”级别,第二个示例覆盖“类”级别...
var Enumerable_first_last = function () {
this.first = function () {
return this[0];
};
this.last = function () {
return this[this.length - 1];
};
};
console.log("(typeof list.first)", (typeof list.first)); // "function" // as expected
console.log("(typeof list.last)", (typeof list.last)); // "undefined" // of course
Enumerable_first_last.call(Array.prototype); // applying behavior to [Array.prototype]
console.log("list.last()", list.last()); // "baz" // due to delegation automatism
如果需要已建立和/或生产就绪的库,则应该仔细查看
这么久
附录一
另请参阅:
附录二
由于我有时显然在摆弄这件事,所以我不想添加一些最后的想法......
没有太多粘合代码(如上所述)的与库无关的方法仅适用于行为重用的非常细粒度的可组合单元。因此,只要不遇到超过 1 或 2 个容易解决的冲突,基于例如Angus Croll 的
Flight Mixins 是值得遵循的道路。
如果涉及到真实的特征,就必须有一个抽象层次。该层(例如作为某种语法糖提供,如 DSL)需要隐藏复杂性,例如从特征中组合特征或在特征应用时解决冲突(当特征的行为应用于对象/类型时)。到目前为止,SO 有 3 个示例,从我的角度来看,它们准确地提供了 OP 所要求的内容……
如何在 javascript 中实现特征?
trait.js 库。他们还有一篇关于一般模式及其具体实现的相当好的文章。我最近将其内置到我的项目中,它的工作就像一个魅力。