2016-07-24 76 views
3

注意,相關Value of this inside object method?Function.prototype.call不將此設置爲Arrow功能

鑑於

var obj = { 
    property: 5, 
    func1: function() { 
    console.log(this.property); 
    }, 
    func2:() => { 
    console.log(this.property); 
    } 
} 

thisWindowobj.func2()

當嘗試使用Function.prototype.call()設置thisobjthis仍然Window

var obj = { 
 
    property: 5, 
 
    func1: function() { 
 
    console.log(this.property); 
 
    }, 
 
    func2:() => { 
 
    console.log(this.property); 
 
    } 
 
} 
 

 
obj.func2.call(obj);

  1. 這是預期的行爲?

  2. 爲什麼Function.prototype.call()沒有設置的context obj.func2obj

+4

'this'爲箭頭功能從外上下文捕獲,所以這是預期的行爲。 – zerkms

+0

@zerkms'Function.prototype.call','Function.prototype.apply'無法設置'context':'this'的箭頭函數? – guest271314

+1

Nope,http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions-runtime-semantics-evaluation – zerkms

回答

4

預計按the standard

一個ArrowFunction爲參數,超好,這或new.target沒有定義本地綁定。在ArrowFunction內對arguments,super,thisnew.target的任何引用必須解析爲在詞彙封閉環境中的綁定。

這意味着 - 你不能設置未定義的東西。

此外,相關:

的函數被稱爲與設置this結合作爲

[[Call]]內部插槽
  • 執行OrdinaryCallBindThis(F, calleeContext, thisArgument)
  • 而這又checks

    1. thisModeF[[ThisMode]]內部槽的值。
    2. 如果thisMode是詞彙,則返回NormalCompletion(undefined)

    所以,在內部具有對功能是否被詞法作用域的額外的檢查(箭頭功能)或沒有。

    參考文獻: