So I've been trying to make a javascript framework for fun. It's been going well so far, but I have one problem: functions with functions added in the prototype.
Code:
const Element = (() => {
function _element(type, comp = [], attr = []) {
const el = document.createElement(type);
comp.forEach(p => el.appendChild(p));
attr.forEach(a => el.setAttribute(a[0], a[1] === undefined ? a[1] : ""));
return el;
}
_element.prototype.event = (name, callback) => {
this.addEventListener(name, callback);
return this; //Not sure what to do to make function chaining possible
}
return _element;
})();
I can use this "class" by using: const element = new Element()
. But when I try to access the function "event" it is undefined. But it does show up with the visual studio code intellisense.
Thank you for your time.
As @Jared Smith pointed out you're overriding the return value of your constructor by returning an html element. Arrow functions also don't give you access to the this
context so chaining wouldn't have worked.
const Element = (() => {
function _element(type, comp = [], attr = []) {
this.el = document.createElement(type);
comp.forEach(p => this.el.appendChild(p));
attr.forEach(a => this.el.setAttribute(a[0], a[1] === undefined ? a[1] : ""));
}
_element.prototype.event = function(name, callback) {
this.el.addEventListener(name, callback);
return this;
}
return _element;
})();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments