繁体   English   中英

定义时绑定箭头功能

[英]Arrow functions bound at definition time

我正在学习es6箭头功能,如何使此测试通过?

describe('arrow functions have lexical `this`, no dynamic `this`', () => {

it('bound at definition time, use `=>` ', function() {
    var bound = new LexicallyBound();
    var fn = () => getFunction();

    assert.strictEqual(fn(), bound);
});

由于getFunction返回的函数没有做任何事情来证明它已关闭this函数,因此我认为在这里使用它没有任何用处。

如果目标是证明箭头函数是按词法绑定的(也就是说,它们在this关闭),则:

it('is lexically bound', function() {
    const obj = {
        arrow: () => {
            return this;
        }
    };
    assert.strictEqual(obj.arrow(), this);
});

如果arrow没有关闭this ,它将返回obj ,而不是该回调中this的当前值。

例:

 function it(label, test) { try { test(); console.log(label, "OK"); } catch (e) { console.log(label, "FAILED", e.message); } } const assert = { strictEqual(a, b) { if (a !== b) { throw new Error("a == b was false"); } } }; it('Arrow function is lexically bound', function() { const obj = { arrow: () => { return this; } }; assert.strictEqual(obj.arrow(), this); }); it('Non-arrow function is not lexically bound', function() { const obj = { nonarrow: function() { return this; } }; assert.strictEqual(obj.nonarrow(), obj); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM