我正在阅读有关箭头函数的内容,发现它们无法更改上下文。
我正在创建一个接收函数然后更改其上下文的模块。但由于用户可能正在输入箭头功能,我无法做到这一点。
所以我想知道,由于无法更改箭头函数上下文,我是否可以复制它的内容并创建一个新函数,它做同样的事情,但现在具有受控上下文。
任何想法如何实现?
一个例子是这样的:
class Foo {
constructor(name) {
this.name = name;
}
sayMyName() {
console.log(this.name);
return this.name;
}
}
class Scope {
constructor(reqId) {
this.foo = new Foo('Hi!');
this.reqId = reqId;
}
do(callback) {
const func = callback.bind(this, this);
func();
}
}
class Controller {
constructor() {
this.foo = new Foo('Hello!');
}
unscoped(req, res, next) {
var a = 1;
res.json({
success: this.foo.sayMyName()
});
}
scoped(req, res, next) {
req.scope.do((ctx) => {
var a = 1;
res.json({
success: this.foo.sayMyName()
});
});
}
}
我想this.foo.sayMyName()返回 'hi'Controller.scoped和 'hello'Controller.unscoped