2016-11-25 40 views
-1

我正在学习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); 
}); 
+0

什么'LexicallyBound'?什么是'getFunction'? –

+0

'class LexicallyBound { getFunction(){ return()=> { return new LexicalBound(); }} getArgumentsFunction(){ 恢复功能(){返回参数}} }' – Bomber

+0

使用 “编辑”,以改善这个问题,不评论。根据这个定义,当你尝试在它前面调用'getFunction'而没有'bound.'时,你应该在你的代码中得到'ReferenceError'。 –

回答

1

因为由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); 
 
});