2015-01-20 72 views
0

我正在尋找爲javascript函數創建公共和私有方法的return語句。使用JavaScript原型的公共方法

我喜歡使用return來傳回可公開訪問的方法,因爲它很容易在一個地方看到所有的公共屬性和方法。

var Base = function(){ 
    var method1 = function(){ 
    console.log("method1"); 
    } 
    var method2 = function(){ 
    console.log("method2"); 
    } 
    //private 
    var method3 = function(){ 
    console.log("method3"); 
    } 
    // public methods 
    return { 
    method1:method1, 
    method2:method2 
    } 
} 
var Child = function(){ 
    var method4 = function(){ 
    console.log("method4"); 
    } 
    var method5 = function(){ 
    console.log("method5"); 
    } 
    //private 
    var method6 = function(){ 
    console.log("method6"); 
    } 
    // public methods 
    return { 
    method4:method4, 
    method5:method5 

    } 
} 
Child.prototype = new Base(); 

var base = new Base(); 
base.method1(); 
base.method2(); 

var child = new Child(); 
try { 
    child.method1(); 
} catch(e){ 
    console.log(e.message); 
} 
try { 
    child.method2(); 
} catch(e){ 
    console.log(e.message); 
} 
child.method4(); 
child.method5(); 

我知道,如果我不喜歡這樣,我會得到公共/私有方法,但我想知道是否有人知道如何與return語句做到這一點。

var Base = function(){ 
    // public methods 
    this.method1 = function(){ 
    console.log("method1"); 
    }; 
    this.method2 = function(){ 
    console.log("method2"); 
    }; 
    // private methods 
    var method3 = function(){ 
    console.log("method2"); 
    }; 
}; 
var Child = function(){ 
    // public methods 
    this.method4 = function(){ 
    console.log("method4"); 
    }; 
    this.method5 = function(){ 
    console.log("method5"); 
    }; 
    // private methods 
    var method6 = function(){ 
    console.log("method6"); 
    }; 
}; 
Child.prototype = new Base(); 

var base = new Base(); 
base.method1(); 
base.method2(); 

var child = new Child(); 
child.method1(); 
child.method2(); 
child.method4(); 
child.method5(); 
+0

在javascript中沒有這樣的私人方法。這是一個固有的矛盾,因爲如果它是一種方法,它不是私人的;它是所有人看到的對象的屬性。 – dandavis 2015-01-20 23:18:00

+1

看看下面的答案,它可能會有所幫助。首先它會解釋爲什麼將Child的原型設置爲Parent的實例顯示了對構造函數和原型的角色缺乏理解,並且它涵蓋了私有函數(在原型上共享)以及特定於實例的模式「protected 「成員http://stackoverflow.com/a/16063711/1641941 – HMR 2015-01-21 01:10:18

回答

1

號,如果你想使用原型繼承不得使用return,你應該使用this,因爲它是從你的原型繼承的實例對象。

當然,沒有什麼能阻止你從你的聚集的公共接口在構造函數的末尾:

function Base() { 
    function method1() { 
    console.log("method1"); 
    } 
    function method2() { 
    console.log("method2"); 
    } 
    //private 
    function method3() { 
    console.log("method3"); 
    } 
    // public methods 
    this.method1 = method1; 
    this.method2 = method2; 
} 

請注意,您should not use new Base for the inheritance of Child.prototype