我想通过一种方法扩展一个元素,但我听说这是个坏主意。因此我想知道是否有可能创建一个类,使其实例具有原型(prototype)中常规元素的所有方法和属性,而不是扩展 DOM 中的所有元素,附加方法将只包含在该类的实例。
示例(不起作用;只是一个概念):
class MyElement {
constructor(element) {
Object.setPrototypeOf(this, element);
}
// Only on elements I declare using this class, not on all HTMLElements
triggerDisplay() {
// This function is an example, all regular HTMLElement properties should work
if (this.style.display === 'none') this.style.display = null;
else this.style.display = 'none';
}
}
我想要实现的是一种像这样将 OOP 与 DOM 一起使用的方法:
// Custom class that inherits from a div element
const myCustomElement = new MyElement(document.getElementById('myDiv'));
// OOP
myCustomElement.triggerDisplay();
代替:
// Regular element
const myNotCustomElement = document.getElementById('myDiv');
// Functional programming
triggerDisplay(myNotCustomElement);
我想要的只是一种通过 DOM 正确使用面向对象编程的方法。在使用函数式编程时,我真的受制于它吗?
如果什么都不管用,用这个好吗:
HTMLDivElement.pprototype.triggerDisplay = function() {
if (this.style.display === 'none') this.style.display = null;
else this.style.display = 'none';
}
?
最佳答案
如果您希望能够在更改 DOM 元素的实例上调用自定义方法,最有意义的方法可能是让类将 DOM 元素保存为实例的属性,然后查找它必要时。例如:
class MyElement {
constructor(element) {
this.element = element;
}
triggerDisplay() {
const { element } = this;
if (element.style.display === 'none') element.style.display = null;
else element.style.display = 'none';
}
}
const myCustomElement = new MyElement(document.getElementById('myDiv'));
myCustomElement.triggerDisplay();
如果你需要能够不通过.element
属性直接引用元素属性,你可以使用原型(prototype)继承将元素设置为实例的内部原型(prototype):
const customProps = {
triggerDisplay: {
value: function() {
const element = Object.getPrototypeOf(this);
if (element.style.display === 'none') element.style.display = null;
else element.style.display = 'none';
}
}
};
const makeCustomElement = (element) => {
return Object.create(element, customProps);
};
const myCustomElement = makeCustomElement(document.getElementById('myDiv'));
myCustomElement.triggerDisplay();
(如果您还想直接在 myCustomElement
上分配属性,则使用另一个 Object.create
包装器,这样分配就不会改变 customProps
对象)
关于javascript - 我如何(并且应该)在 DOM 对象上创建额外的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57833119/