我正在阅读有关箭头功能的内容,并发现它们的上下文无法更改。
我正在创建一个接收函数的模块,然后更改其上下文。但由于用户可能正在输入箭头功能,我无法实现它。
所以我想知道,由于无法更改箭头函数上下文,我可以复制其内容并创建一个新功能,但是现在具有受控上下文。
任何想法如何实现?
一个例子是这样的:
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()
在Controller.scoped
中返回'hi',在Controller.unscoped
中返回'hello'
答案 0 :(得分:2)
可以在箭头功能上使用Function.prototype.bind
,Function.prototype.call
和Function.prototype.apply
来更改其上下文。
var arrowFunc = () => {console.log(this === myObject);};
var functionExpression = function() { console.log(this === myObject); };
var myObject = { id : "sampleObject"};
var boundFunctionExpression = functionExpression.bind(myObject);
console.log("Function expression bound with Function.prototype.bind :");
boundFunctionExpression();
var boundArrowFunc = arrowFunc.bind(myObject);
console.log("Arrow function bound with Function.prototype.bind :");
boundArrowFunc();
console.log("Arrow function called with Function.prototype.call :");
arrowFunc.call(myObject);
console.log("Arrow function called with Function.prototype.apply :");
arrowFunc.apply(myObject, []);
所以不,我认为你不能做到这一点。
More on the differences between arrow function and function expressions / declarations.