Javascript 特性模式资源 [英] Javascript Traits Pattern Resources
问题描述
有人可以推荐在 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.
我在 SO 上看到了这篇文章,还有其他方法吗?javascript 中的特征
I came across this post on SO, are there any other approaches? Traits in javascript
也欢迎任何真实世界的例子.
Any real world examples would be welcome as well.
谢谢.
推荐答案
我会建议一些简单的,大致如下:
I would suggest something simple, along the lines of:
让特征定义为标准的 JavaScript 对象.
Let traits be defined as standard JavaScript objects.
var equalsTrait = {
eq: function(obj) {
return this == obj
},
neq: function(obj) {
return ! this.eq(obj)
}
};
编写一个函数,用您的特征扩展给定的类(并将其绑定到全局范围内的合理位置):
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];
}
}
}
这篇关于Javascript 特性模式资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!