简体   繁体   English

定义时绑定箭头功能

[英]Arrow functions bound at definition time

I'm learning es6 arrow functions, how I can get this test to pass? 我正在学习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);
});

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

If the goal is to prove that arrow functions are lexically bound (that is, that they close over this ), then: 如果目标是证明箭头函数是按词法绑定的(也就是说,它们在this关闭),则:

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. 如果arrow没有关闭this ,它将返回obj ,而不是该回调中this的当前值。

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

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

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