I want to pass the Class instance itself into a function using function.apply and I use this
keyword for the first pram of function.apply; however, the function sees WIndow Object instead Class instance when run a validation logic.
class T {
transform(handler = {}) {
const newHandler = {};
const methods = Object.getOwnPropertyNames(handler);
for (const method of methods) {
newHandler[method] = (...args) => {
return handler[method].apply(this, args || []);
}
}
return newHandler;
}
}
const transformer = new T();
transformer.name = "John"
const transformed = transformer.transform({
printName: () => {
if("toString" in this && this.toString() == "[object Window]") {
console.log("this is Window")
} else {
console.log(`You are ${this.name}`);
}
}
});
transformed.printName();