[英]Public methods using prototype with JavaScript
I am looking to create public and private methods for javascript functions with return statements. 我正在寻找使用return语句为javascript函数创建公共和私有方法。
I like the idea of using return to pass back the publicly accessible methods because it easy to see all of your public properties and methods in one place. 我喜欢使用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();
I know if I do it like this I will get the public/private methods, but I was wondering if anyone knew how to do it with the return statement. 我知道如果这样做,我将获得公共/私有方法,但是我想知道是否有人知道如何使用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();
No. You must not use return
if you want to use prototypical inheritance, you should use this
as it is the instance object that inherits from your prototype. 不能。如果要使用原型继承,则不能使用
return
,而应使用this
因为它是从原型继承的实例对象。
Of course, nothing prevents you from congregating your public interface in the end of the constructor: 当然,没有什么可以阻止您将公共接口聚集在构造函数的末尾:
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;
}
Notice that you should not use new Base
for the inheritance of Child.prototype
. 请注意,您不应使用
new Base
继承Child.prototype
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.