Javascript define class - javascript

What is the best way to define a class? I am aware of the fact that this is most of the times a choice of what you prefer to use, but what is the direct difference between these 3 examples?
Example 1
var Class = (function(){
function Class() {
this.test = 'test'
}
return Class;
})();
var c = new Class();
console.log(typeof Class);
console.log(c.test);
Example 2
var Class2 = function(){
this.test = 'test'
};
var c2 = new Class2();
console.log(typeof Class2);
console.log(c2.test);
Example 3
function Class3(){
this.test = 'test'
};
var c3 = new Class3();
console.log(typeof Class3);
console.log(c3.test);
Sometimes I use it like this as well:
var Class = (function(){
var Private = {}, Public = {};
Private._doSomething = function() {
// something
}
Public.doSomethingElse = function() {
// something else
}
return Public;
})();

Note: The main answer below was written in 2012. See the end for additional notes regarding JavaScript's own class feature (ES2015+).
"Best" is an inherently subjective thing, but I'll try to point out some information about each and let you make up your own mind about "best."
Example 1
...gives you a handy scope (the anonymous function) where you can put truly private class-wide information (and utility functions) which only the Class functions have access to:
var Class = (function(){
var trulyPrivateInformation = 42;
function trulyPrivateUtilityFunction() {
// ...
}
function Class() {
this.test = 'test';
}
return Class;
})();
Example 1 is not "hoisted." It is processed as part of the step-by-step code.
The Class function will have a real name.
Example 2
...creates a function that has no name and assigns it to a variable that has a name. Modern browsers are pretty smart about it, but in theory at least, the function is anonymous, which impacts what information your tools can provide you. that (as of ES2015) has a name (Class2) except in obsolete environments like IE. It doesn't have the private class-wide scope Example 1 has.
Like Example 1, Example 2 is processed as part of the step-by-step code, not hoisted.
Example 3
...is just Example 1 without the private class-wide scope, but it's also "hoisted" — the Class function is defined before any step-by-step code is executed. That means this works:
var c = new Class();
console.log(c.test); // Logs 'test'
function Class() {
this.test = 'test';
}
Note that even though Class is defined lower down, it's done before the code above runs. This isn't true of either Example 1 or Example 2.
As with Example 1 (but not 2), the Class function has a real name.
In 2015, JavaScript got its own class syntax. Here in 2019, it's natively supported by all modern browsers, and you can transpile with tools like Babel if you need to support IE. Here's how class would relate to the OP's question:
Example 1 with class
const Class = (() => {
let trulyPrivateInformation = 42;
function trulyPrivateUtilityFunction() {
// ...
}
return class Class {
constructor() {
this.test = 'test';
}
}
})();
Processed in the step-by-step execution of code. Has truly private scope (within the anonymous scoping function) for truly private stuff. Has a proper name.
Example 2 with class (which is also Example 3 with class)
class Class2 {
constructor() {
this.test = 'test';
}
}
let c2 = new Class2();
console.log(typeof Class2);
console.log(c2.test);
Processed in the step-by-step execution of code. Doesn't have the truly private scope Example 1 has (though private fields and methods are coming soon). Has a proper name.

Related

Method Inheritance in JavaScript

JavaScript uses a Prototype system, which is fundamentally different than a Class system. This is my first serious encounter with the language. I had fooled around with it previously, but this is the first time I built a system with proper OO, inheritance, polymorphism, etc.
From what I read there seems to be a few common methods to do member function inheritance in Javascript. Assuming you have a parent foo as following
foo = function(){ this.one = 1; }
foo.prototype.func1 = function(){return this.one;}
The MDN Introduction to JavaScript Inheritance suggests the naive approach of invoking the parent's method in the context of the child, as shown below.
bar = function(){ foo.call(this); }
bar.prototype = Object.create(foo.prototype);
bar.prototype.func1 = function(){ return this.one + foo.prototype.func1();}
This has the advantage of being simple to understand, but can become cumbersome as pointed out in this Salsify Blog post. The blog post outlines an alternate method where a super property is defined in the child prototype, and the name of each member function is attached as a property to the method. This method, however, relies on the caller property of a method, which the article points out will soon be deprecated. Rather than duplicate the entire post, I believe a summary of the important points are these
Object.defineProperty(bar.prototype, "super", {
get: function get() {
...
// methodName is set as a property on each method in an omitted code segment
methodName = get.caller.methodName;
...
Object.getPrototypeOf(this.prototype)[methodName]
}
}
Which is to say that you find the method with the same name in your prototype's prototype. I was wondering if this can be done in a simpler manner, without having to attach the method name as a parameter and without the Function.caller.
foo.prototype.super = function(method) {
superMethod = Object.getPrototypeOf(this.constructor.prototype)[method];
return superMethod.call(this, Array.prototype.slice.call(arguments, 1));
}
bar.prototype.func1 = function(){ return this.one + super('func1'); }
I'm making a number of assumptions in the above, I'd like to verify some assumptions.
new bar().constructor.prototype === Object.getPrototypeOf(new bar())
If the above is always true, is one preferable over the other?
The Parent's member function will always live in the child's prototype's prototype (assuming that neither of the prototypes were mutated after object creation)
That Object.getPrototypeOf() is not the "language support for accessing super methods" that the blog refers to as being added in ES6
If Object.getPrototypeOf() isn't that language support, what is?
After seeing the error of using this, which does not change throughout the execution and always refers to the instance of the subclass, I've revisited and am thinking I need something like this
Grandfather = function(){};
Grandfather.prototype.function1 = function(){console.log("I am the Grandfather");};
Father = function(){Grandfather.apply(this);};
Father.prototype = Object.create(Grandfather.prototype);
Father.prototype.function1 = function f(){ f.super(); console.log("I am the Father");};
Father.prototype.function1.super = Grandfather.prototype.function1;
Child = function(){Father.apply(this);}
Child.prototype = Object.create(Father.prototype);
Child.prototype.function1 = function f(){ f.super(); console.log("I am the Child");};
Child.prototype.function1.super = Father.prototype.function1;
c = new Child();
c.function1();
// I am the Grandfather
// I am the Father
// I am the Child
And so the question becomes, how to set the super property on to each function in some automatic way?
One such way to do this is shown below, it has the benefit that functions added to the prototype after objects are instantiated still receive the benefit of being able to call superFunc, whereas an approach that sets a super property at class extension time would not set such a property if functions are added to the prototype later.
The downsides of this approach are that it only works in single threaded environment and that it requires functionality inherited from a common base class. It is not threadsafe since some state is held in a what is effectively a static variable of the function. This is fine for my purposes since browsers still have single threaded JavaScript. The requirement that all classes inherit from some base class containing this method isn't a huge blocker (especially if you do a "bad thing" and insert this into Object's prototype).
Grandfather.prototype.superFunc = function f(funcName){
currentPrototype = Object.getPrototypeOf(f.startingPrototype || Object.getPrototypeOf(this));
f.startingPrototype = currentPrototype;
return currentPrototype[funcName]();
}
Child.prototype.function2 = function(){this.superFunc('function2'); console.log("Still in the Child");};
Father.prototype.function2 = function(){this.superFunc('function2'); console.log("Still in the Father");};
GrandFather.prototype.function2 = function(){console.log("Still in the Grandfather");};
c = new Child();
c.function2();
// Still in the Grandfather
// Still in the Father
// Still in the Child
Question 1
new Bar().constructor.prototype should equal Object.getPrototypeOf(new Bar()), provided you haven't overrided Bar.prototype.constructor or Bar.prototype, or return a different object in the Bar constructor. Here's an example:
function Bar() {}
var foo = new Bar();
foo.constructor.prototype === Object.getPrototypeOf(foo); // true
function Bar2() {}
var foo2 = new Bar2();
Bar2.prototype = {};
foo2.constructor.prototype === Object.getPrototypeOf(foo2); // false
function Bar3() {}
var foo3 = new Bar3();
Bar3.prototype.constructor = function NotBar3() {};
foo3.constructor.prototype === Object.getPrototypeOf(foo3); // false
Question 2
If you're looking to get the actual prototype of an object, use Object.getPrototypeOf, as that's unaffected by any of the changes shown above.
Question 3
No, you will not be able to access Foo from new Bar(). In your example, new Bar() would not inherit from Foo.prototype and as a result, there's no way to access Foo unless you make it inherit from Foo.prototype or assign Foo to a property of new Bar() or Bar.prototype.
Question 4/5
No, that's not what they're referring to. ES6 will introduce a separate class contruct, where super takes on a special meaning (similar to how super works in other languages with classes). Here's an example of how classes work in ES6:
class Foo {
constructor() {
this.one = 1;
}
func1() {
return this.one;
}
}
class Bar extends Foo {
func1() {
return this.one + super();
}
}
When you use super in the way you do it'll break when inheritance is more than 2 levels.
Assuming you'd use it the following way:
//changed super to this.super since super is not shown to exist in global scope
bar.prototype.func1(){ return this.one + this.super('func1'); }
See the following example:
function GrandFather(){
this.i = 0;
};
GrandFather.prototype.test = function(){
console.log('test in GrandFather');
};
function Father(){
GrandFather.call(this);
};
Father.prototype = Object.create(GrandFather.prototype);
Father.prototype.constructor = Father;
Father.prototype.super = GrandFather.prototype;
Father.prototype.test = function(){
console.log('test in Father');
//prevent too many recursions
this.i++;
if(this.i>5){
return;
}
this.super.test.call(this);//because test in child was called
// with Child instance as invoking object this will be Child
// and this.super will be Father.prototype
};
function Child(){
Father.call(this);
}
Child.prototype = Object.create(Father.prototype);
Child.prototype.constructor = Child;
Child.prototype.super = Father.prototype;
Child.prototype.test = function(){
console.log('test in Child');
this.super.test.call(this);//because invoking object is Child
//this.super in Father is Child
};
var c = new Child();
c.test();
It's also common practice to start a constructor function with a capital so it's better to use Foo and Bar for constructor function names.
If you want to go through all the trouble of simulating super in JavaScript then the following way would be slightly more robust: http://ejohn.org/blog/simple-javascript-inheritance/

Javascript Class Constructor Call Method

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

Where should private methods be placed when using the JavaScript Module pattern?

I've started using the Module pattern in a project of mine. As I understand it, it goes something like this:
var obj = (function(foo){
//Some initialization logic up here.
//Private methods
var privateBazz = function(){
return "I'm known only to this closure!";
}();
//Public methods
return {
publicFoo: foo,
publicBar: function(){
return foo + privateBazz;
}
}
})();
This looked pretty good on paper and, in practice, seems to work reasonably well. Initialization logic at the top is intuitive, then private methods, then public.
I've encountered one issue, though. How should I call publicFoo or publicBar from outside the scope of the return statement and inside the scope of obj's function declaration?
My current solution is to do something like:
var obj = (function(foo){
//Private methods declared early for use.
var privateBazz = function(){
return "I'm known only to this closure!";
}();
var privateBar = function(){
return foo + privateBazz;
};
//Some initialization logic up here.
var dependentOnBar = privateBar();
//Public methods
return {
publicFoo: foo,
publicBar: privateBar
}
})();
This works, but suddenly the declarations of my private variables are placed above my objects private property declarations. The problem becomes exacerbated if I attempt to keep the private function declarations as close to the code which first calls them, so I have just been declaring all the private functions I need at the top, then initializing properties afterwards. Again, this works, but I am used to having code as close to the execution point as possible. So, declaring blocks of private functions at the top is really awkward to me. Does anyone else feel this way, or is this something I just need to get over for JavaScript? Are there any steps I should be taking when I see this happening?
It sounds like you could solve this problem by simply not using object notation to return the module, but rather initialize it and build it as you go. This would go something like this:
var obj = (function(foo){
var self = {};
//Some initialization logic up here.
//Private properties
var foo = "only accessible within this scope";
//Private methods
var privateBazz = function(){
return "I'm known only to this closure!";
}();
//Public Properties
self.publicFoo = foo;
//Public Methods
self.publicBar = function(){
return foo + privateBazz;
};
return self;
})();
here is my solution: if you declare everything before the return as a "private" method and make public those you want to, then you can call your private from within the public and vice versa (in your first sample, your privates can't call the publics as they are not declared at that moment)
var obj = (function() {
// All functions now have direct access to each other
var privateFunc = function() {
return "private "+publicFunc1();
};
var publicFunc1 = function() {
return "public 1 ";
};
var publicFunc2 = function() {
return "public 2 "+publicFunc1();
};
var publicFunc3 = function() {
return "public 3 "+privateFunc();
};
// Return the object that is assigned to Module
return {
publicFunc1: publicFunc1,
publicFunc3: publicFunc3,
publicFunc2: publicFunc2
};
}());
alert(obj.publicFunc3());
If you emulate CommonJS Modules, you can assign properties to the exports object as well as accessing them from elsewhere within the IIFE scope via qualified or unqualified name.
(function (exports, undefined) {
var priv1 = 42;
exports.pubOne = function () {};
var localAlias = function () {};
localAlias(42);
exports.pubTwo = localAlias;
})(window.App);
In this example, Window.App might be my namespaced global object for this module, but you could pass in an empty object or some deeply nested namespace just as easily.

How to define a common variable in javascript Class that can be used across instances?

I want to define a single variable used among all instances in the Class definition(which is a plain function constructor in a jQuery plugin).
Is there such a feature?
If there is,just a simple demo and I think I'll understand.
What you're looking for is essentially a private static or protected static variable, which can't be 100% emulated in javascript (that I know of).
You can make public static or private, though.
tehMick's solution gives you public static with some convenience setters/getters, but it's really no different than if you replaced y.setB(2) with A.b = 2.
Here's how a private variable would work, but understand that this is still a per instance variable, and reflects the same value via the getter only because each instance sets it to the same literal string.
function SomeClass()
{
var privateVariable = 'foo';
this.publicVariable = 'bar';
this.getPrivateVariable = function()
{
return privateVariable;
}
this.setPrivateVariable = function( value )
{
privateVariable = value;
}
}
SomeClass.staticVariable = 'baz';
var a = new SomeClass();
var b = new SomeClass();
// Works...
alert( a.getPrivateVariable() );
alert( b.getPrivateVariable() );
// Until we try to set it...
a.setPrivateVariable( 'hello' );
// Then it breaks
alert( a.getPrivateVariable() );
alert( b.getPrivateVariable() );
Javascript doen't really provide that kind of data hiding, but this may suit your purposes:
function A()
{
if (!A.b) A.b = 1;//shared
//this.b = 0;//not shared
}
A.prototype.getB = function()
{
return A.b;//shared
//return this.b;//not shared
}
A.prototype.setB = function(value)
{
A.b = value;//shared
//this.b = value//not shared
}
function load()
{
var x = new A();
var y = new A();
y.setB(2);
document.body.innerHTML += x.getB();
}
output: 2
Your question is not very clear. Do you mean a global variable? A variable that can be accessed from any object?
EDIT (based on comments)
You can do something like this to make the variables scoped to just your code:
//This function will execute right away (it is basically the same as leaving it out,
//except that anything inside of it is scoped to it.
(function(){
var globalToThisScope = "this is global ONLY from within this code section";
window.object = {
//Now any instance of this object can see that variable,
// but anything outside of the outer empty function will not see anything
};
})();
I concur with Peter Bailey (+1). Douglas Crockford has a discussion of public and private instance variables; Peter suggests a nice way to add static public variables.

Javascript private member on prototype

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

Categories

Resources