To make a JavaScript class with a public method I\'d do something like:
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something
JavaScript uses prototypes and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.
Wikipedia quote:
Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; when a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.
Solution using a self invoking function and the call function to call the private "method" :
var MyObject = (function () {
// Constructor
function MyObject (foo) {
this._foo = foo;
}
function privateFun (prefix) {
return prefix + this._foo;
}
MyObject.prototype.publicFun = function () {
return privateFun.call(this, '>>');
}
return MyObject;
})();
var myObject = new MyObject('bar');
myObject.publicFun(); // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
The call function allows us to call the private function with the appropriate context (this).
If you are using node.js, you don't need the IIFE because you can take advantage of the module loading system:
function MyObject (foo) {
this._foo = foo;
}
function privateFun (prefix) {
return prefix + this._foo;
}
MyObject.prototype.publicFun = function () {
return privateFun.call(this, '>>');
}
exports.MyObject = MyObject;
Load the file:
var MyObject = require('./MyObject').MyObject;
var myObject = new MyObject('bar');
myObject.publicFun(); // Returns '>>bar'
myObject.privateFun('>>'); // ReferenceError: private is not defined
The bind operator :: is an ECMAScript proposal and is implemented in Babel (stage 0).
export default class MyObject {
constructor (foo) {
this._foo = foo;
}
publicFun () {
return this::privateFun('>>');
}
}
function privateFun (prefix) {
return prefix + this._foo;
}
Load the file:
import MyObject from './MyObject';
let myObject = new MyObject('bar');
myObject.publicFun(); // Returns '>>bar'
myObject.privateFun('>>'); // TypeError: myObject.privateFun is not a function