2017-01-25 64 views
0

我哈瓦簡單JS功能在javascript中訪問私有函數的方法?

var myFunction=function(){ 
    var age=20; 
    this.name="bar"; 
    var show=function(){ 
     console.log(age); 
    } 
} 

和像創建實例

var obj=new myFunction(); 
console.log(obj.show()) 

日誌:this

如何我解決這個問題?我試圖搜索這個,但無法找到我的解決方案。 UPDATE 我希望所有私人成員保持不變。

+1

'show'不是obj'的'的成員。它是'myFunction'的局部變量。 – CollinD

+1

將'var show'變成'this.show',以便可以在myFunction的實例上訪問 – Damon

+0

爲什麼要做'console.log(obj.show())'?不'show()'*已經*調用'console.log()'? –

回答

0

試着改變你的代碼

var myFunction=function(){ 
var age=20; 
this.name="bar"; 
this.show=function(){ 
console.log(age); 
} 
} 

改變你的表演變種是一個財產

0

一個乾淨的解決方案是使函數公開作爲對象屬性來訪問:

var myFunction = function() { 
 
    var age = 20; 
 
    this.name = "bar"; 
 
    
 
    this.show = function() { 
 
    console.log(age); 
 
    } 
 
} 
 

 
var obj = new myFunction(); 
 
obj.show();

0

使用var您聲明show作爲變量而不是myFunction的成員。 與age同樣的,如果它是一個類的成員,你也應該使用this

這一種方式來改變它:

var myFunction = function() { 
 
    this.age = 20; 
 
    this.name="bar"; 
 
    this.show = function() { 
 
     console.log(age); 
 
    } 
 
} 
 

 
var obj = new myFunction(); 
 
console.log(obj.name); 
 
obj.show();
在這裏找到更多的信息: best approach to member variables in object-oriented javascript?

3

的您的代碼存在的問題是show方法在myFunction的功能範圍之外無法訪問。

在Javascript中,範圍在函數中定義(忽略ES6塊範圍)。因此,變量age,nameshow的範圍在該函數內。但是,當您使用this並使用構造函數(new)時,新創建的對象包含與this關鍵字關聯的屬性。在你的情況下,你只將name屬性與新對象相關聯,並且沒有將show函數與this相關聯。

其中一個解決方案是使用模塊模式。您可以通過返回封裝了公開提供的屬性的對象來製作公共訪問屬性。因此,就您的情況而言,您可以從myFunction中公開nameshow方法。另外,不需要執行兩次console.log。您可以通過obj.show()獲得輸出。否則它會記錄undefined作爲show函數不會返回任何內容。

var myFunction=function(){ 
 
    var age=20; 
 
    var name="bar"; 
 
    var show=function(){ 
 
     console.log(age); 
 
    } 
 
    
 
    return { 
 
     name : name, 
 
     show : show, 
 
    } 
 
} 
 

 
var obj=new myFunction(); 
 
obj.show()