2015-11-17 31 views
8

我有一個函數只能在一個類中使用,並且不希望它可以在類之外訪問。如何在ES6類中聲明本地函數?

class Auth { 
    /*@ngInject*/ 
    constructor($http, $cookies, $q, User) { 
    this.$http = $http; 
    this.$cookies = $cookies; 
    this.$q = $q; 
    this.User = User; 

    localFunc(); // Need to create this function, and need it to be accessible only inside this class 
    } 
} 

我所做到目前爲止被宣告類

function localFunc() { 
    return 'foo'; 
} 
class Auth { 
    ... 
} 

外的函數。然而,這是它污染了全球功能並不好,但我裹着這裏面IIFE。那麼,有沒有辦法在ES6類中創建一個本地函數?

+3

如果您使用的是ES6模塊加載器,則在該類之外聲明該函數將不會污染全局範圍。這是確保私有函數在ES6 – CodingIntrigue

+1

@MichałPerłakowski我不認爲它是重複的,[建議規範](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6類)處理*有狀態的,特定於實例的屬性*不是函數/方法。 – Bergi

回答

13

沒有,有沒有辦法在class聲明局部功能。您當然可以聲明(靜態)輔助方法,並使用下劃線前綴將它們標記爲「私有」,但這可能不是您想要的。你總是可以在方法中聲明局部函數。

但是,如果你需要多次,那麼唯一的辦法就是把它放在class旁邊。如果你正在編寫腳本,IEFE將像往常一樣需要。如果你正在編寫一個ES6模塊(這是首選解決方案),那麼隱私是微不足道的:只是不要export的功能。

+0

如果將函數放在類的旁邊,它將無法訪問'this',因此您必須將其作爲參數傳遞。 –

+0

@DanDascalescu當然,我認爲OP有意要求一個*函數*,儘管不是*方法*。 – Bergi

0

你可以使用一個符號:

const localFunc = Symbol(); 
class Auth { 
    /*@ngInject*/ 
    constructor($http, $cookies, $q, User) { 
    this.$http = $http; 
    this.$cookies = $cookies; 
    this.$q = $q; 
    this.User = User; 

    this[localFunc] = function() { 
     // I am private 
    }; 
    } 
} 
+1

符號不是私人的。 – Bergi