简体   繁体   中英

Arrow functions bound at definition time

I'm learning es6 arrow functions, how I can get this test to pass?

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

Since the function returned by getFunction doesn't do anything to demonstrate that it closes over this , I don't think it's of any use to use you here.

If the goal is to prove that arrow functions are lexically bound (that is, that they close over this ), then:

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

If arrow didn't close over this , it would return obj , not the current value of this in that callback.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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