2016-10-27 24 views
-1

爲什麼setTimeout中的this不等於在使用箭頭函數時調用渲染函數的對象?JavaScript - 帶有箭頭函數的超時時間

class X { 
     constructor(config) { 
     this.data = config.data; 
     this.render_ = config.render; 
     } 
     render() { 
     this.render_(this.data); 
     } 
    } 
    var x = new X({ 
     data: [1, 2, 3], 
     render: (data) => { 
     setTimeout(() => { 
      console.log(this); 
     }, 200); 
     } 
    }); 
    x.render(); 

回答

2

閱讀說arrow function documentation的一部分「箭函數作爲方法」

在總結

:箭頭的功能只是單純的不綁定this或自己的this版本,而是引用全局窗口目的。

+0

這個問題似乎是關於'this',而不是'arguments'。 –

+0

已更新@FelixKling我正在看上面的部分:') – httpNick

2

因爲arrow functions詞彙約束。這意味着他們在宣佈時承擔「這個」的價值。它們不受修改this值的其他方式的影響,包括被稱爲方法或函數,如bind,applycall

function F() { 
 
    this.type = 'F'; 
 
    this.logTypeExpression = function() { 
 
    console.log(this.type); 
 
    }; 
 
    this.logTypeArrow =() => { 
 
    console.log(this.type); 
 
    }; 
 
} 
 

 
function G() { 
 
    this.type = 'G'; 
 
} 
 

 
var f = new F(); 
 
var g = new G(); 
 

 
f.logTypeExpression(); // F 
 
f.logTypeArrow(); // F 
 

 
// Now lets give these functions to G 
 
g.logTypeExpression = f.logTypeExpression; 
 
g.logTypeArrow = f.logTypeArrow; 
 

 
g.logTypeExpression(); // G 
 
g.logTypeArrow(); // F(!) (That's because `this` was assigned by the arrow function)

0

在所創建的箭頭功能的時間,this不綁定到任何對象,因此它仍然是指window。如果你想引用那個特定的實例,也許你想嘗試console.log(x);

+0

這應該是一個評論,至多。問題在於'this'沒有引用'x'對象。 –

0

下面的代碼僅保存對使用對象文字語法創建的函數的引用。

this.render_ = config.render; 

使用綁定(本)會告訴函數調用你的X對象的實例函數時使用的參數對象作爲此引用。

class X { 
    constructor(config) { 
     this.data = config.data; 
     this.render_ = config.render.bind(this); 
    } 
    render() { 
     this.render_(this.data); 
    } 
} 

此外,它是否是你的代碼片段中的箭頭函數或常規函數表達式無關緊要。