2016-11-25 111 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); 
 
});

相關問題