添加Native Array原型方法 [英] Adding Native Array prototype methods
问题描述
我想在 Array.prototype
中添加两个方法,它们的工作方式有点像jQuery的addClass / removeClass。这就是我写的:
I'd like to add two methods in the Array.prototype
which will work a bit like addClass / removeClass of jQuery. This is what I've written:
Array.prototype.addClass = function (className) {
this.forEach((element) => {
element.classList.add(className);
});
};
Array.prototype.removeClass = function (className) {
this.forEach((element) => {
element.classList.remove(className);
});
};
我被告知添加方法来构建JS原型通常是一个坏主意,所以我很想知道什么是最好的替代方案,以避免潜在的陷阱。
I was told it's generally a bad idea to add methods to built in JS prototypes, so I was wondering what the best alternatives would be to avoid potential gotchas.
我的想法:
- 检查方法是否已存在
- 只需创建一个带有2个参数的正常函数,数组和类名
- 创建我的新自定义对象,它将具有我构建的DOM操作方法
我也在看 https://github.com/franciscop/umbrella/blob/master/src/plugins/addclass/addclass.js 以及它是如何实现的。
I am also looking at https://github.com/franciscop/umbrella/blob/master/src/plugins/addclass/addclass.js and how it's implemented.
推荐答案
是的,有时我们喜欢在内置的JS原型中有一些额外的方法。在这些情况下,我检查它是否已经存在,如果不存在,你应该使用 Object.defineProperty
,以便该方法不可枚举:
Yeah, sometimes we love to have some extra methods in the built in JS prototypes. In these situations I check if it already exists and if not you should use Object.defineProperty
so that the method is not enumerable:
if (!Array.prototype.addClass)
Object.defineProperty(Array.prototype, 'addClass', {
value: function(className) {
this.forEach((element) => {
element.classList.add(className);
});
}
})
您可以查看 mozilla的文档。
这篇关于添加Native Array原型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!