0

我正在阅读有关箭头函数的内容,发现它们无法更改上下文。

我正在创建一个接收函数然后更改其上下文的模块。但由于用户可能正在输入箭头功能,我无法做到这一点。

所以我想知道,由于无法更改箭头函数上下文,我是否可以复制它的内容并创建一个新函数,它做同样的事情,但现在具有受控上下文。

任何想法如何实现?

一个例子是这样的:

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

4

1 回答 1

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, []);

所以不,我不认为你能做到这一点。

更多关于箭头函数和函数表达式/声明之间的区别。

于 2018-05-29T14:14:11.473 回答