为什么"this"没有与函数一起传递.apply



我想使用function.apply将class实例本身传递到一个函数中,并且我使用this关键字作为函数.apply的第一个pram;但是,当运行验证逻辑时,函数会看到WIndow Object而不是Class实例。

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();

它可能必须处理词法范围如何使用箭头函数。

https://medium.com/hackernoon/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

transformer.transform函数内部的箭头函数在添加到转换器之前似乎绑定到了窗口。通过将其更改为使用function关键字,它不再将其this绑定到窗口并显示所需的结果。

class T {
transform = (handler = {}) => {
const newHandler = {};
const methods = Object.getOwnPropertyNames(handler);
for (const method of methods) {
newHandler[method] = handler[method].bind(this);
}
return newHandler;
}
}
const transformer = new T();
transformer.name = "John"
const transformed = transformer.transform({
printName: function () {
if(this === window) {
console.log("this is Window")
} else {   
console.log(`You are ${this.name}`);
}
}
});
transformed.printName();

最新更新