I am looking to create public and private methods for javascript functions with return statements.
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.
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.
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();