我希望为带有 return 语句的 javascript 函数创建公共(public)和私有(private)方法。
我喜欢使用 return 传回可公开访问的方法的想法,因为可以轻松地在一个地方查看所有公共(public)属性和方法。
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();
我知道如果我这样做,我会得到公共(public)/私有(private)方法,但我想知道是否有人知道如何使用 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();
最佳答案
没有。如果您想使用原型(prototype)继承,则不能使用 return
,而应该使用 this
,因为它是从原型(prototype)继承的实例对象。
当然,没有什么可以阻止您在构造函数的末尾聚合公共(public)接口(interface):
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
.
关于javascript - 通过 JavaScript 使用原型(prototype)的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28056181/