2015-01-20 76 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