簡體   English   中英

像正常功能一樣使用箭頭功能

[英]using arrow function like a normal function

我喜歡新箭頭()=>{}語法,我想盡可能地使用它。 我知道箭頭功能指向此頂點的外部。 有沒有辦法像普通功能一樣使用箭頭功能? 我只需要使this指向箭頭功能的內部即可。

我需要編寫以下代碼:

let foo = () => {
 // "this" keyword should point to the inner of that function, not window object
}

像這樣的代碼工作:

function foo() {
 // "this" keyword points to the inner of that class/object/function/whatever-it-calls-fix-me-if-am-i-wrong
}

是可以實現的還是我需要堅持使用function關鍵字?

更具體地說,我需要this東西使其與Angular中的controllerAs語法一起使用,但這不是重點。 與其說是AngularJS問題,不如說是JS問題。

有沒有辦法像普通功能一樣使用箭頭功能? 我只需要使此指向箭頭功能的內部即可。

不合理 ,不。 實際上,沒有。 :-)使用function功能。

它不能工作,因為箭頭功能關閉了this 這意味着調用者無法設置this ,這在幾種情況下是需要的(例如原型上的函數,設置this jQuery之類的庫的回調等)。

如何將箭頭函數與使用此函數的庫一起使用

let _self = this;
something.each(function() {
    console.log(_self); 
    console.log(this); 
});

參考: https : //basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM