Pass a Class
function callMethods(evt) {
const e = new evt
e.one()
e.two()
}
callMethods(class {
one() {
console.log('one')
}
two() {
console.log('two')
}
})
This is so tempting for something I want to do… but too strange to use probably… maybe…
function callMethods(evt) {
const e = new evt
e.one()
e.two()
}
callMethods(class {
one() {
console.log('one')
}
two() {
console.log('two')
}
})
This is so tempting for something I want to do… but too strange to use probably… maybe…
class Person {
constructor(name, email) {
this.name = name;
}
toString() {
return `name: ${this.name}`;
}
}
class Teacher extends Person {
constructor(name, subject) {
super(name);
this.subject = subject;
}
toString() {
return super.toString() + ` subject: ${this.subject}`;
}
}
const teacher = new Teacher('testname', 'testSubject');
console.log(teacher.toString());
This is from an old stackoveflow answer of mine…
function bindAll(target) {
const keys = Object.getOwnPropertyNames(target.constructor.prototype);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const propOrMethod = target[key];
if (typeof propOrMethod === 'function') {
target[key] = target[key].bind(target);
}
}
}
class Test {
constructor() {
bindAll(this);
document.addEventListener('click', this.onClick);
}
onClick(e) {
console.log('click', this);
}
otherMethod(e) {
console.log('test', this);
}
}
const test = new Test();
setInterval(test.otherMethod, 1000);
This is useful when you know you need many methods of a given class to be bound to the classes instance. Another way to do this is to selectively use instance properties:
class Test {
constructor() {
document.addEventListener('click', this.onClick);
}
onClick = e => {
console.log('click', this);
}
otherMethod e => {
console.log('test', this);
}
}
Avoiding classes is another way to not have to deal with this issue 😉