In Java you could call methods to help you do some heavy lifting in the constructor, but javascript requires the method to be defined first, so I'm wondering if there's another way I could go about this or if I'm forced to call the method that does the heavy lifting after it's been defined. I prefer to keep instance functions contained within the Object/Class, and it feels weird that I would have to have the constructor at the very end of the object/class.
function Polynomials(polyString)
{
// instance variables
this.polys = [];
this.left = undefined;
this.right = undefined;
// This does not work because it's not yet declared
this.parseInit(polyString);
// this parses out a string and initializes this.left and this.right
this.parseInit = function(polyString)
{
//Lots of heavy lifting here (many lines of code)
}
// A lot more instance functions defined down here (even more lines of code)
// Is my only option to call it here?
}
Here's what I would do:
var Polynomials = function() {
// let's use a self invoking anonymous function
// so that we can define var / function without polluting namespace
// idea is to build the class then return it, while taking advantage
// of a local scope.
// constructor definition
function Polynomials( value1) (
this.property1 = value1;
instanceCount++;
// here you can use publicMethod1 or parseInit
}
// define all the public methods of your class on its prototype.
Polynomials.prototype = {
publicMethod1 : function() { /* parseInit()... */ },
getInstanceCount : function() ( return instanceCount; }
}
// you can define functions that won't pollute namespace here
// those are functions private to the class (that can't be accessed by inheriting classes)
function parseInit() {
}
// you can define also vars private to the class
// most obvious example is instance count.
var instanceCount = 0;
// return the class-function just built;
return Polynomials;
}();
Remarks:
Rq 1:
prototype functions are public methods available for each instance of the class.
var newInstance = new MyClass();
newInstance.functionDefinedOnPrototype(sameValue);
Rq2:
If you want truly 'private' variable, you have to got this way:
function Constructor() {
var privateProperty=12;
this.functionUsingPrivateProperty = function() {
// here you can use privateProperrty, it's in scope
}
}
Constructor.prototype = {
// here define public methods that uses only public properties
publicMethod1 : function() {
// here privateProperty cannot be reached, it is out of scope.
}
}
personally, I do use only properties (not private vars), and use the '' common convention to notify a property is private. So I can define every public method on the prototype.
After that, anyone using a property prefixed with '' must take his/her responsibility , it seems fair. :-)
For the difference between function fn() {} and var fn= function() {}, google or S.O. for this question, short answer is that function fn() {} gets the function defined and assigned its value in whole scope, when var get the var defined, but its value is only evaluated when code has run the evaluation.
Your 'instance variables' are declared on the 'this' object which if you're looking for a Java equivalent is a bit like making them public. You can declare variables with the var keyword which makes them more like private variables within your constructor function. Then they are subject to 'hoisting' which basically means they are regarded as being declared at the top of your function (or whatever scope they are declared in) even if you write them after the invoking code.
I would create a function declaration and then assign the variable to the function declaration. The reason being that JavaScript will hoist your function declarations.
So you could do this:
function Polynomials(polyString) {
// instance variables
this.polys = [];
this.left = undefined;
this.right = undefined;
// this parses out a string and initializes this.left and this.right
this.parseInit = parseInitFunc;
// This does not work because it's not yet declared
this.parseInit(polyString);
// A lot more instance functions defined down here (even more lines of code)
function parseInitFunc(polyString) {
console.log('executed');
}
// Is my only option to call it here?
}
That way your code stays clean.
jsFiddle
Related
I'm trying to understand how public` properties in the (Revealing) Module Pattern work. An advantage pointed out by Carl Danley "The Revealing Module Pattern" is:
Explicitly defined public methods and variables which lead to increased readability
Let's take a look at this code (fiddle):
var a = function() {
var _private = null;
var _public = null;
function init() {
_private = 'private';
_public = 'public';
}
function getPrivate() {
return _private;
}
return {
_public : _public,
init : init,
getPrivate : getPrivate,
}
}();
a.init();
console.log( a._public ); // null
console.log( a.getPrivate() ); // "private"
It returns null when calling a._public. I now can manipulate that public property, like a._public = 'public';. But I can't change it from within my object. Or at least those changes aren't passed through. I was kinda expecting it to be "public" as it was updated by the init-method before.
Does this actually mean, that I can't have any methods, that handle public properties? Then public properties in this pattern make little sense, right? I also tried this without luck (fiddle):
return {
_pubic : _public,
init2 : function() {
_public = 'public';
}
}
Last, but not least, I have a question regarding the whole return statement. Why isn't it possible to just use return this; to make everything public? As this should be the context of the self-invoked function, shouldn't it just return eveyrthing in it? Why do I have to create another object, that is returned? In this fiddle it returns the window object.
Does this actually mean, that I can't have any methods, that handle public properties?
No, it means that you cannot have public variables. var _public is a variable, and it is not accessible from outside, and when you modify the private variable this will not be reflected in your public ._public property.
If you want to make things public, use properties:
var a = function() {
var _private = null;
function init() {
_private = 'private';
this._public = 'public';
}
function getPrivate() {
return _private;
}
return {
_public : null,
init : init,
getPrivate : getPrivate,
}
}();
I can manipulate that public property, like a._public = 'public';. But I can't change it from within my object.
You can use this in the methods of your object, as shown above. Or you use a to reference the object, or possibly even store a local reference to the object you return. See here for the differences.
Or at least those changes aren't passed through
Yes, because variables are different from properties (unlike in some other languages like Java, and with exceptions for global ones). When you export public: _public in your object literal, it takes only the current value from the _public variable and creates a property on the object with it. There is no persistent reference to the variable, and changes to one are not reflected in the other.
Why isn't it possible to just use return this; to make everything public? As this should be the context of the self-invoked function, shouldn't it just return eveyrthing in it?
Variables are part of a scope in JavaScript. (Except for the global one) those scopes are not objects accessible to the language.
The this keyword does not refer to this scope of the function, but to the context that was provided by the call. That can be the base reference in a method call, the new instance in a constructor invocation, or just nothing in a basic function call like yours (or the global window object in loose mode).
In your module definition, _public is copied by value, because in javascript, only objects are assigned by reference. After that it has no link to the local _public variable whatsoever. This would therefore only work if you either "box" the _public in an object, so it gets copied by reference, or you refer to the object's property within your module as well, having only one reference to the local variable:
var a = function() {
var module = {
_public: null
};
// use module._public here
return module;
}();
a._public = "foo";
You can use this construction for creating new class
function a(){
var _private = null;
this.public = null;
this.getPrivate = function(){
return _private;
};
function init(){
_private = "private";
this.public = "public";
}
init.apply(this, arguments);
}
//static function
a.create = function(){
return new a();
};
//using
var b = new a();
//or
var b = a.create();
Using the below construct you can have private variables, public & private functions. So why have all the various ways to create a namespace ?
Is the NameSpace that radically different than a function with associated behavior & scope ?
I see the point of not polluting the global namespace e.g. window object in browsers with the plethora of functions one would create, but that can be achieved by the below as well..
Seems I'm missing a fundamental point..
// Constructor for customObject
function customObject(aArg, bArg, cArg)
{
// Instance variables are defined by this
this.a = aArg;
this.b = bArg;
this.c = cArg;
}
// private instance function
customObject.prototype.instanceFunctionAddAll = function()
{
return (this.a + this.b + this.c);
}
/*
Create a "static" function for customObject.
This can be called like so : customObject.staticFunction
*/
customObject.staticFunction = function()
{
console.log("Called a static function");
}
// Test customObject
var test = new customObject(10, 20, 30);
var retVal = test.instanceFunctionAddAll();
customObject.staticFunction();
The point is that you might have more than one function, but you only want to pollute the global scope with a single variable (the "namespace").
// Wrap in a immediately-executing anonymous function to avoid polluting
// the global namespace unless we explicitly set properties of window.
(function () {
function CustomObject(/*...*/) { /*...*/ }
// Add methods, static methods, etc. for CustomObject.
function CustomObject2(/*...*/) { /*...*/ }
// Add methods, static methods, etc. for CustomObject2.
var CONSTANT_KINDA = "JavaScript doesn't really have constants";
// Create a namespace, explicitly polluting the global scope,
// that allows access to all our variables local to this anonymous function
window.namespace = {
CustomObject: CustomObject,
CustomObject2: CustomObject2,
CONSTANT_KINDA: CONSTANT_KINDA
};
}());
Also, Felix is right, your "private" instance function is actually very public. See Crockford's "Private Members in JavaScript" if you want actual private methods.
// i = inner, o = outer, f=function, a=attribute
var singleton = function() {
var iF = function() {
return this.oA; // returns undefined
}
return {
oF: function() {
this.oA = true;
return iF();
},
oA: false
};
}();
singleton.oF();
If singleton were a class (as in a class-based language), shouldn't I be able to access oA through this.oA?
The only way I've found of accessing oA from iF is by doing:
return singleton.oA; // returns true (as it should)
I don't know why, but accessing oA through the singleton base object makes me feel kind of... dirty. What am I missing? What is this.oA actually referring to (in a scope sense of view)?
The main point here is that there are no classes in javascript. You need to live without them. You can only emulate some of their characteristics.
The this keyword in javascript refers to the object which invoked the function. If it is a function in the global object this will refer to window. If it is a constructor function and you invoke it with the new keyword, this will refer to the current instance.
There is a simple thing you can do, if you want to keep oA public, and access it from a private function.
// i = inner, o = outer, f=function, a=attribute
var singleton = (function() {
// public interface
var pub = {
oF: function() {
this.oA = true;
return iF();
},
oA: false
};
// private function
var iF = function() {
return pub.oA; // returns public oA variable
}
// return public interface
return pub;
})();
Notice that I wrapped the whole singleton function in parens. The reason this convention is so popular is that it helps you to know if a function will be executed immediately (as in this case). Imagine if your function gets bigger, and when you look at the code it wouldn't be obvious if singleton is a function or an object that a self-invoking function returns. If you've got the parens however, it is obvious that singleton will be something that the function returns immediately.
I just read a few threads on the discussion of singleton design in javascript. I'm 100% new to the Design Pattern stuff but as I see since a Singleton by definition won't have the need to be instantiated, conceptually if it's not to be instantiated, in my opinion it doesn't have to be treated like conventional objects which are created from a blueprint(classes). So my wonder is why not just think of a singleton just as something statically available that is wrapped in some sort of scope and that should be all.
From the threads I saw, most of them make a singleton though traditional javascript
new function(){}
followed by making a pseudo constructor.
Well I just think an object literal is enough enough:
var singleton = {
dothis: function(){},
dothat: function(){}
}
right? Or anybody got better insights?
[update] : Again my point is why don't people just use a simpler way to make singletons in javascript as I showed in the second snippet, if there's an absolute reason please tell me. I'm usually afraid of this kind of situation that I simplify things to much :D
I agree with you, the simplest way is to use a object literal, but if you want private members, you could implement taking advantage of closures:
var myInstance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
About the new function(){} construct, it will simply use an anonymous function as a constructor function, the context inside that function will be a new object that will be returned.
Edit: In response to the #J5's comment, that is simple to do, actually I think that this can be a nice example for using a Lazy Function Definition pattern:
function singleton() {
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
When the function is called the first time, I make the object instance, and reassign singleton to a new function which has that object instance in it's closure.
Before the end of the first time call I execute the re-defined singleton function that will return the created instance.
Following calls to the singleton function will simply return the instance that is stored in it's closure, because the new function is the one that will be executed.
You can prove that by comparing the object returned:
singleton() == singleton(); // true
The == operator for objects will return true only if the object reference of both operands is the same, it will return false even if the objects are identical but they are two different instances:
({}) == ({}); // false
new Object() == new Object(); // false
I have used the second version (var singleton = {};) for everything from Firefox extensions to websites, and it works really well. One good idea is to not define things inside the curly brackets, but outside it using the name of the object, like so:
var singleton = {};
singleton.dothis = function(){
};
singleton.someVariable = 5;
The ES5 spec lets us use Object.create():
var SingletonClass = (function() {
var instance;
function SingletonClass() {
if (instance == null) {
instance = Object.create(SingletonClass.prototype);
}
return instance;
}
return {
getInstance: function() {
return new SingletonClass();
}
};
})();
var x = SingletonClass.getInstance();
var y = SingletonClass.getInstance();
var z = new x.constructor();
This is nice, since we don't have to worry about our constructor leaking, we still always end up with the same instance.
This structure also has the advantage that our Singleton doesn't construct itself until it is required. Additionally, using the closure as we do here prevents external code from using our "instance" variable, accidentally or otherwise. We can build more private variables in the same place and we can define anything we care to export publically on our class prototype.
The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. 1
(function (global) {
var singleton;
function Singleton () {
// singleton does have a constructor that should only be used once
this.foo = "bar";
delete Singleton; // disappear the constructor if you want
}
global.singleton = function () {
return singleton || (singleton = new Singleton());
};
})(window);
var s = singleton();
console.log(s.foo);
var y = singleton();
y.foo = "foo";
console.log(s.foo);
You don't just declare the singleton as an object because that instantiates it, it doesn't declare it. It also doesn't provide a mechanism for code that doesn't know about a previous reference to the singleton to retrieve it. The singleton is not the object/class that is returned by the singleton, it's a structure. This is similar to how closured variables are not closures, the function scope providing the closure is the closure.
I am just posting this answer for people who are looking for a reliable source.
according to patterns.dev by Lydia Hallie, Addy Osmani
Singletons are actually considered an anti-pattern, and can (or.. should) be avoided in JavaScript.
In many programming languages, such as Java or C++, it's not possible to directly create objects the way we can in JavaScript. In those object-oriented programming languages, we need to create a class, which creates an object. That created object has the value of the instance of the class, just like the value of instance in the JavaScript example.
Since we can directly create objects in JavaScript, we can simply use
a regular object to achieve the exact same result.
I've wondered about this too, but just defining an object with functions in it seems reasonable to me. No sense creating a constructor that nobody's ever supposed to call, to create an object with no prototype, when you can just define the object directly.
On the other hand, if you want your singleton to be an instance of some existing "class" -- that is, you want it to have some other object as its prototype -- then you do need to use a constructor function, so that you can set its prototype property before calling it.
The latter code box shows what I've seen JS devs call their version of OO design in Javascript.
Singetons are meant to be singular objects that can't be constructed (except, I suppose, in the initial definition. You have one, global instance of a singleton.
The point of using the "pseudo constructor" is that it creates a new variable scope. You can declare local variables inside the function that are available inside any nested functions but not from the global scope.
There are actually two ways of doing it. You can call the function with new like in your example, or just call the function directly. There are slight differences in how you would write the code, but they are essentially equivalent.
Your second example could be written like this:
var singleton = new function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
this.dothis = function () {
return privateVariable;
};
this.dothat = function () {};
}; // Parentheses are allowed, but not necessary unless you are passing parameters
or
var singleton = (function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
return {
dothis: function () {
return privateVariable;
},
dothat: function () {}
};
})(); // Parentheses are required here since we are calling the function
You could also pass arguments to either function (you would need to add parentheses to the first example).
Crockford (seems to) agree that the object literal is all you need for a singleton in JavaScript:
http://webcache.googleusercontent.com/search?q=cache:-j5RwC92YU8J:www.crockford.com/codecamp/The%2520Good%2520Parts%2520ppt/5%2520functional.ppt+singleton+site:www.crockford.com&cd=1&hl=en&ct=clnk
How about this:
function Singleton() {
// ---------------
// Singleton part.
// ---------------
var _className = null;
var _globalScope = null;
if ( !(this instanceof arguments.callee) ) {
throw new Error("Constructor called as a function.");
}
if ( !(_className = arguments.callee.name) ) {
throw new Error("Unable to determine class name.")
}
_globalScope = (function(){return this;}).call(null);
if ( !_globalScope.singletons ) {
_globalScope.singletons = [];
}
if ( _globalScope.singletons[_className] ) {
return _globalScope.singletons[_className];
} else {
_globalScope.singletons[_className] = this;
}
// ------------
// Normal part.
// ------------
var _x = null;
this.setx = function(val) {
_x = val;
}; // setx()
this.getx = function() {
return _x;
}; // getx()
function _init() {
_x = 0; // Whatever initialisation here.
} // _init()
_init();
} // Singleton()
var p = new Singleton;
var q = new Singleton;
p.setx(15);
q.getx(); // returns 15
I stole this from CMS / CMS' answer, and changed it so it can be invoked as:
MySingleton.getInstance().publicMethod1();
With the slight alternation:
var MySingleton = { // These two lines
getInstance: function() { // These two lines
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
console.log( "b" );
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
console.log( "a" );
},
publicMethod2: function () {
// ...
privateMethod();
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
}
Well I tried to figure out is this possible in any way. Here is code:
a=function(text)
{
var b=text;
if (!arguments.callee.prototype.get)
arguments.callee.prototype.get=function()
{
return b;
}
else
alert('already created!');
}
var c=new a("test"); // creates prototype instance of getter
var d=new a("ojoj"); // alerts already created
alert(c.get()) // alerts test
alert(d.get()) // alerts test from context of creating prototype function :(
As you see I tried to create prototype getter. For what? Well if you write something like this:
a=function(text)
{
var b=text;
this.getText=function(){ return b}
}
... everything should be fine.. but in fact every time I create object - i create getText function that uses memory. I would like to have one prototypical function lying in memory that would do the same... Any ideas?
EDIT:
I tried solution given by Christoph, and it seems that its only known solution for now. It need to remember id information to retrieve value from context, but whole idea is nice for me :) Id is only one thing to remember, everything else can be stored once in memory. In fact you could store a lot of private members this way, and use anytime only one id. Actually this is satisfying me :) (unless someone got better idea).
someFunc = function()
{
var store = new Array();
var guid=0;
var someFunc = function(text)
{
this.__guid=guid;
store[guid++]=text;
}
someFunc.prototype.getValue=function()
{
return store[this.__guid];
}
return someFunc;
}()
a=new someFunc("test");
b=new someFunc("test2");
alert(a.getValue());
alert(b.getValue());
JavaScript traditionally did not provide a mechanism for property hiding ('private members').
As JavaScript is lexically scoped, you could always simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.
Of course, there are ways to work around this, but I wouldn't recommend it:
Foo = (function() {
var store = {}, guid = 0;
function Foo() {
this.__guid = ++guid;
store[guid] = { bar : 'baz' };
}
Foo.prototype.getBar = function() {
var privates = store[this.__guid];
return privates.bar;
};
Foo.prototype.destroy = function() {
delete store[this.__guid];
};
return Foo;
})();
This will store the 'private' properties in another object seperate from your Foo instance. Make sure to call destroy() after you're done wih the object: otherwise, you've just created a memory leak.
edit 2015-12-01: ECMAScript6 makes improved variants that do not require manual object destruction possible, eg by using a WeakMap or preferably a Symbol, avoiding the need for an external store altogether:
var Foo = (function() {
var bar = Symbol('bar');
function Foo() {
this[bar] = 'baz';
}
Foo.prototype.getBar = function() {
return this[bar];
};
return Foo;
})();
With modern browsers adopting some ES6 technologies, you can use WeakMap to get around the GUID problem. This works in IE11 and above:
// Scope private vars inside an IIFE
var Foo = (function() {
// Store all the Foos, and garbage-collect them automatically
var fooMap = new WeakMap();
var Foo = function(txt) {
var privateMethod = function() {
console.log(txt);
};
// Store this Foo in the WeakMap
fooMap.set(this, {privateMethod: privateMethod});
}
Foo.prototype = Object.create(Object.prototype);
Foo.prototype.public = function() {
fooMap.get(this).p();
}
return Foo;
}());
var foo1 = new Foo("This is foo1's private method");
var foo2 = new Foo("This is foo2's private method");
foo1.public(); // "This is foo1's private method"
foo2.public(); // "This is foo2's private method"
WeakMap won't store references to any Foo after it gets deleted or falls out of scope, and since it uses objects as keys, you don't need to attach GUIDs to your object.
Methods on the prototype cannot access "private" members as they exist in javascript; you need some kind of privileged accessor. Since you are declaring get where it can lexically see b, it will always return what b was upon creation.
After being hugely inspired by Christoph's work-around, I came up with a slightly modified concept that provides a few enhancements. Again, this solution is interesting, but not necessarily recommended. These enhancements include:
No longer need to perform any setup in the constructor
Removed the need to store a public GUID on instances
Added some syntactic sugar
Essentially the trick here is to use the instance object itself as the key to accessing the associated private object. Normally this is not possible with plain objects since their keys must be strings. However, I was able to accomplish this using the fact that the expression ({} === {}) returns false. In other words the comparison operator can discern between unique object instances.
Long story short, we can use two arrays to maintain instances and their associated private objects:
Foo = (function() {
var instances = [], privates = [];
// private object accessor function
function _(instance) {
var index = instances.indexOf(instance), privateObj;
if(index == -1) {
// Lazily associate instance with a new private object
instances.push(instance);
privates.push(privateObj = {});
}
else {
// A privateObject has already been created, so grab that
privateObj = privates[index];
}
return privateObj;
}
function Foo() {
_(this).bar = "This is a private bar!";
}
Foo.prototype.getBar = function() {
return _(this).bar;
};
return Foo;
})();
You'll notice the _ function above. This is the accessor function to grab ahold of the private object. It works lazily, so if you call it with a new instance, it will create a new private object on the fly.
If you don't want to duplicate the _ code for every class, you can solve this by wrapping it inside a factory function:
function createPrivateStore() {
var instances = [], privates = [];
return function (instance) {
// Same implementation as example above ...
};
}
Now you can reduce it to just one line for each class:
var _ = createPrivateStore();
Again, you have to be very careful using this solution as it can create memory leaks if you do not implement and call a destroy function when necessary.
Personally, I don't really like the solution with the guid, because it forces the developer to declare it in addition to the store and to increment it in the constructor. In large javascript application developers might forget to do so which is quite error prone.
I like Peter's answer pretty much because of the fact that you can access the private members using the context (this). But one thing that bothers me quite much is the fact that the access to private members is done in a o(n) complexity. Indeed finding the index of an object in array is a linear algorithm. Consider you want to use this pattern for an object that is instanciated 10000 times. Then you might iterate through 10000 instances each time you want to access a private member.
In order to access to private stores in a o(1) complexity, there is no other way than to use guids. But in order not to bother with the guid declaration and incrementation and in order to use the context to access the private store I modified Peters factory pattern as follow:
createPrivateStore = function () {
var privates = {}, guid = 0;
return function (instance) {
if (instance.__ajxguid__ === undefined) {
// Lazily associate instance with a new private object
var private_obj = {};
instance.__ajxguid__ = ++guid;
privates[instance.__ajxguid__] = private_obj;
return private_obj;
}
return privates[instance.__ajxguid__];
}
}
The trick here is to consider that the objects that do not have the ajxguid property are not yet handled. Indeed, one could manually set the property before accessing the store for the first time, but I think there is no magical solution.
I think real privacy is overrated. Virtual privacy is all that is needed. I think the use of _privateIdentifier is a step in the right direction but not far enough because you're still presented with a listing of all the _privateIdentifiers in intellisense popups. A further and better step is to create an object in the prototype and/or constructor function for segregating your virtually private fields and methods out of sight like so:
// Create the object
function MyObject() {}
// Add methods to the prototype
MyObject.prototype = {
// This is our public method
public: function () {
console.log('PUBLIC method has been called');
},
// This is our private method tucked away inside a nested privacy object called x
x: {
private: function () {
console.log('PRIVATE method has been called');
}
},
}
// Create an instance of the object
var mo = new MyObject();
now when the coder types "mo." intellisense will only show the public function and "x". So all the private members are not shown but hidden behind "x" making it more unlikely for a coder to accidentally call a private member because they'll have to go out of their way and type "mo.x." to see private members. This method also avoids the intellisense listing from being cluttered with multiple private member names, hiding them all behind the single item "x".
I know this thread is really really old now, but thought this solution might be of interest to anyone passing by:
const Immutable = function ( val ) {
let _val = val;
this.$ = {
_resolve: function () {
return _val;
}
};
};
Immutable.prototype = {
resolve: function () {
return this.$._resolve();
}
};
Essentially hiding the internal _val from being manipulated and making an instance of this object immutable.
I have created a new library for enabling private methods on the prototype chain.
https://github.com/TremayneChrist/ProtectJS
Example:
var MyObject = (function () {
// Create the object
function MyObject() {}
// Add methods to the prototype
MyObject.prototype = {
// This is our public method
public: function () {
console.log('PUBLIC method has been called');
},
// This is our private method, using (_)
_private: function () {
console.log('PRIVATE method has been called');
}
}
return protect(MyObject);
})();
// Create an instance of the object
var mo = new MyObject();
// Call its methods
mo.public(); // Pass
mo._private(); // Fail