Javascript 特征模式资源

发布于 2024-11-28 03:46:13 字数 257 浏览 2 评论 0原文

有人可以推荐在 javascript 中使用 Trait 的好资源吗?经过一番搜索后,我主要找到有关提供特征功能的库的文章,但我很好奇如何在没有库的情况下实现特征的最佳实践。

我在 SO 上看到这篇文章,还有其他方法吗? javascript 中的特征

任何现实世界的例子也将受到欢迎。

谢谢。

Could anyone recommend good resources for using traits in javascript? After some searching I mainly find articles about libraries that provide traits functionality, but I was curious about best practices on how to implement traits without a library.

I came across this post on SO, are there any other approaches?
Traits in javascript

Any real world examples would be welcome as well.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

简美 2024-12-05 03:46:13

我建议一些简单的建议,大致如下:

  1. 让特征定义为标准 JavaScript 对象。

    var equalsTrait = {
        eq: 函数(obj) {
            返回 this == obj
        },
        neq: 函数(obj) {
            返回 ! this.eq(obj)
        }
    };
    
  2. 编写一个函数来使用您的特征扩展给定的类(并将其绑定到全局范围内的合理位置):

    window.Traits = {};
    Traits.addToClass = 函数(traits, cls) {
        for (var key in 特征) {
            if (cls.prototype[key]) {
                Alert("Class " + cls + " 已经有一个名为 " + key + "!");
            }
            别的 {
                cls.prototype[key] = 特征[key];
            }
        }
    }
    
  3. 利润!

I would suggest something simple, along the lines of:

  1. Let traits be defined as standard JavaScript objects.

    var equalsTrait = {
        eq: function(obj) {
            return this == obj
        },
        neq: function(obj) {
            return ! this.eq(obj)
        }
    };
    
  2. Write a function to extend a given class with your traits (and bind it to a sensible location in the global scope):

    window.Traits = {};
    Traits.addToClass = function(traits, cls) {
        for (var key in traits) {
            if (cls.prototype[key]) {
                alert("Class " + cls + " already has a method named " + key + "!");
            }
            else {
                cls.prototype[key] = traits[key];
            }
        }
    }
    
  3. Profit!

生来就爱笑 2024-12-05 03:46:13

有关 trait.js 库中特征的一些(有限)信息

与 Javascript 无关,但关于继承系统和特征的好论文“特征:A细粒度复用机制”。实现细节的描述可以在“将特征应用于 Smalltalk Collection Hierarchy 中找到”。 本页上列出了更多此类论文。

Some (limited) information about traits in the trait.js library

Not about Javascript, but a good paper about inheritance systems and traits "Traits: A Mechanism for Fine-grained Reuse". A description of implementation details can be found in "Applying Traits to the Smalltalk Collection Hierarchy". More papers of this type listed on this page.

可可 2024-12-05 03:46:13

两篇描述 JavaScript 的基于库无关纯函数的 Mixin 和 Trait 方法的论文是 对 JavaScript Mixins 的全新审视,作者:Angus Croll,2011 年 5 月和 JavaScript 的众多才能用于推广面向角色的编程方法,例如 Traits 和 Mixins(从 4 月份开始) 2014 年。

这么长的

附录

一请参阅:

附录二

从不时开始我显然在摆弄这个问题,我不想添加一些最终的想法......

没有太多粘合代码(如上所述)的库不可知方法仅适用于行为重用的非常细粒度的可组合单元。因此,只要不遇到超过 1 或 2 个容易解决的冲突,基于 Angus Croll 的 Flight Mixins 的模式就是可遵循的路径。

如果涉及到真实的特征,就必须有一个抽象层次。该层(例如作为某种语法糖提供,如 DSL)需要隐藏复杂性,例如从特征组合特征或在特征应用时(当特征的行为应用于对象/类型时)解决冲突。

到目前为止,SO 中有 3 个例子,从我的角度来看,它们准确地提供了 OP 所要求的内容……

任何现实世界的例子也将受到欢迎。

  • stackoverflow.com :: JS 中的组合和混合
  • stackoverflow.com : :<一href="https://stackoverflow.com/questions/30732241/mixins-for-es6-classes-transpiled-with-babel/43129978#43129978">ES6 类的 Mixins,用 babel 转译
  • stackoverflow.com : :<一href="https://stackoverflow.com/questions/43027388/refactoring-legacy-mixin-based-class-hierarchies/43059101#43059101">重构遗留的基于 mixin 的类层次结构
  • stackoverflow.com :: 使用类的多重继承

Two papers that do describe library agnostic pure function based Mixin and Trait approaches for JavaScript are A fresh look at JavaScript Mixins by Angus Croll from May 2011 and The many talents of JavaScript for generalizing Role Oriented Programming approaches like Traits and Mixins from April 2014.

so long

Appendix I

please see also:

Appendix II

Since from time to time I'm apparently fiddle with this matter I wan't to add some final thoughts to it ...

The library agnostic approach without too much glue code (as mentioned above) does work only for very fine grained composable units of behavioral reuse. Thus, as long as one does not run into more than 1 or 2 easily resolvable conflicts, patterns based on e.g. Angus Croll's Flight Mixins are the path to follow.

If it comes to real traits, there has to be an abstraction level to it. This layer (e.g. provided as some sort of syntactic sugar like a DSL) needs to hide the complexity e.g. of composing traits from traits or of conflict resolution at a traits apply time (when a trait's behavior gets applied to an object/type).

By now there are 3 examples at SO that from my perspective provide exactly what the OP did ask for …

Any real world examples would be welcome as well.

紧拥背影 2024-12-05 03:46:13

您可以使用函数来实现特征,而无需库。

请参阅工作示例特征+继承

感谢dbarbeau

// Usage __traits(TargetClass, Trait1, Trait2, ...);
// Mix multiple definitions as traits. Properties will be overwritten if names are duplicating. 
function __traits(mixtureTarget) {
    for(var a=1; a < arguments.length; ++a) {
        var mixin = arguments[a];
        for (var p in mixin){ if (mixin.hasOwnProperty(p)){ mixtureTarget[p] = mixin[p]; } };
        Object.getOwnPropertyNames(mixin.prototype).forEach( function(name) {
            mixtureTarget.prototype[name] = mixin.prototype[name];
        });
    }; 
};

You can use function to implement traits without a library.

See working example Traits + Inheritance

Thanks to dbarbeau

// Usage __traits(TargetClass, Trait1, Trait2, ...);
// Mix multiple definitions as traits. Properties will be overwritten if names are duplicating. 
function __traits(mixtureTarget) {
    for(var a=1; a < arguments.length; ++a) {
        var mixin = arguments[a];
        for (var p in mixin){ if (mixin.hasOwnProperty(p)){ mixtureTarget[p] = mixin[p]; } };
        Object.getOwnPropertyNames(mixin.prototype).forEach( function(name) {
            mixtureTarget.prototype[name] = mixin.prototype[name];
        });
    }; 
};
清旖 2024-12-05 03:46:13

npm 中有一个简单且轻量级的包用于此目的。你可以在这里查看,它确实使 PHP 功能的特征可以轻松地在 Javascript 上实现。

https://github.com/regs37/trait.js

// create a simple trait that you want to be reusable
const MyTrait = trait({
  sampleTrait: function(){
    return "trait";
  }
})

// lets have a sample class User
class User {

}

// we will inherit the trait to the User Class
MyTrait.in(User);

// sample instance of the user
let user = new User();

// try to call he trait we have inherited
console.log(user.sampleTrait()); // trait
<script src="https://unpkg.com/[email protected]/build/trait.min.js"></script>

there is simple and lightweight a package in npm for this. you can check it here, it really made trait from PHP feature easily get implemented on Javascript.

https://github.com/regs37/trait.js

// create a simple trait that you want to be reusable
const MyTrait = trait({
  sampleTrait: function(){
    return "trait";
  }
})

// lets have a sample class User
class User {

}

// we will inherit the trait to the User Class
MyTrait.in(User);

// sample instance of the user
let user = new User();

// try to call he trait we have inherited
console.log(user.sampleTrait()); // trait
<script src="https://unpkg.com/[email protected]/build/trait.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文