How to access private properties from an IFFE in javascript - javascript

I was playing with the idea of using an IFFE inside a object declaration instead of an init() method that I have to manually invoke at the end of the declaration. The only problem I seem to be having is that I don't know how to access private properties from within the IFFE. Take the following example:
function Obj() {
this.prop = 'Public property';
var _prop = 'Private property';
( function( that ) {
console.log( that.prop );
console.log( that._prop ); // Returns undefined
} )( this );
}
obj = new Obj();
by passing this into the IFFE I can access the this scope but the private properties do not seem to be assessable through this. I know I could manually pass individual properties in, but I would prefer a solution that allows me access to all private properties.
What is the best way to solve this?

As #jherax said the purpose of using an IFFE is to approximate block level scope in JavaScript so accessing a private property outside of an IFFE defeats the purpose of having one.
However you could create an API of sorts by returning an object which points to the properties in question. Used improperly this is a bit of a hack and is generally discouraged.
function Obj() {
this.prop = 'Public property';
var _prop = 'Private property';
( function( that ) {
console.log( that.prop );
console.log( that._prop ); // Returns undefined
} )( this );
return {
accessPoint: _prop //gives you a getter of sorts to _prop
};
}
obj = new Obj();
obj.accessPoint;

IIFE is the way as the Module Pattern is implemented. (See The Module Pattern)
Any object declared inside a function is isolated from the outer scope, maning that private variables are unaccessible. If you need to modify private objects, you can reconsider using an IIFE.
Now take a look at your code, the variable _prop is declared in the same closure where the IFFE is defined, meaning that you can access that object within the IIFE, e.g.
function Obj() {
var _private = 1;
//IIFE
(function() {
console.log("_private: ", _private);
}());
}
Also, you may create a public method that modifies the private object, e.g.
function Obj() {
var _seed = 0;
this.setSeed = function (seed) {
_seed = seed;
};
this.getSeed = function() {
return _seed;
};
}
Or you can define a getter / setter in the instance prototype, but this approach has the disadvantage to have a lower performance, e.g.
function Obj() {
var _seed = 0;
Object.defineProperty(this, "seed", {
get: function () { return _seed; },
set: function (seed) {
//ensure to be a numeric value
if (+seed || seed === 0) _seed = +seed;
}
});
}
Or creating a module with loose augmentation
//begin IIFE
var module = (function (module) {
var _private = 1;
function getPrivate() {
return _private;
}
function setPrivate(value) {
_private = value;
}
function printPublicMember() {
console.log(module.publicMember);
}
//public mudule API
module = {
"publicMember": "I am public!!",
"printPublicMember": printPublicMember,
"getPrivate": getPrivate,
"setPrivate": setPrivate
};
return module;
}(window.module || {}));
//end IIFE

Because:
var _prop = 'Private property';
creates a local variable and
console.log( that._prop ); // Returns undefined
is attempting to access the _prop property of that (aka this). Variables are not object properties*. Use:
console.log( _prop ); // Returns Private property
Well, variables are properties of a VariableEnvironment which belongs to a LexicalEnvironment, a kind of object (in ECMA-262 ed 3 it was called a variable object) but you can't access those directly in the way you can access variables as properties of the global or window object.

The IIFE inside your constructor has no meaning whatsoever. It is exactly equivalent to just writing its contents directly. The purpose of an IIFE is to create an enclosed scope with local variables, which you don't have.
In what way is this IFFE supposed to avoid having to call some init function? The constructor is already an init function in its own way.
The reason you can't access that._prop from within your IIFE is that there is no instance property called _prop. There is a local variable called _prop, To access it, simply say _prop, not this._prop or that._prop.

Related

(Revealing) Module Pattern, public variables and return-statement

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();

Why private variables in an anonymous function are accessible from outside the function in javascript?

After reading a piece of "Essential JS Design Patterns" book, I can't understand the behavior of private variables in this code:
var SingletonTester = (function () {
// options: an object containing configuration options for the singleton
// e.g var options = { name: "test", pointX: 5};
function Singleton( options ) {
// set options to the options supplied
// or an empty object if none are provided
options = options || {};
// set some properties for our singleton
this.name = "SingletonTester";
this.pointX = options.pointX || 6;
this.pointY = options.pointY || 10;
}
// our instance holder
var instance;
// an emulation of static variables and methods
var _static = {
name: "SingletonTester",
// Method for getting an instance. It returns
// a singleton instance of a singleton object
getInstance: function( options ) {
if( instance === undefined ) {
instance = new Singleton( options );
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({
pointX: 5
});
// Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );
This is an example given by the book about the Singleton pattern.
There is a anonymous function, which return an object containing the "name" member and the "getInstance" method for returning the instance of "Singleton" function.
My troumble is understand how the object stored in SingletonTester can access to the "instance" private var. I mean, after the anonymous function has done its job, the SingletonTester variable should hold only the object:
{
name: "SingletonTester",
// Method for getting an instance. It returns
// a singleton instance of a singleton object
getInstance: function( options ) {
if( instance === undefined ) {
instance = new Singleton( options );
}
and this object does not know what instance is. Same thing for the instantiation of "Singleton" function. How does it know what function is "Singleton", which was defined in the scope of the anonymous function?
What you're experiencing is lexical scoping in JavaScript. Basically, whenever you execute a function, you have access to that function's scope. In addition to that though, you also have access to the lexical scope in which the function was defined.
Let's take a look at an example:
var someObject = (function () {
var privateVariable = 18;
var getValue = function () {
return privateVariable;
};
return {
getValue: getValue
};
})();
The object 'someObject' has a method 'getValue' which when executed returns the value 18. But how is this possible? Here's how the JavaScript engine works when you try executing someObject.getValue():
The JavaScript engine performs a property lookup on the someObject object and sees that it has its own getValue property.
Once it's located the function object (getValue), it executes the function.
When the function gets executed, the JavaScript engine tries to lookup the value for privateVariable.
However, within the scope of the 'getValue' function, privateVariable doesn't exist.
Therefore, the JavaScript engine looks to the PARENT scope (i.e. the scope in which the getValue function was declared).
This scope corresponds to the scope from the anonymous function. And within this scope, privateVariable has a value of 18.
That's lexical scoping in JavaScript. Regarding your example, this is why the instance of SingletonTester has access to the "instance" variable.
I HIGHLY recommend this book to learn more: Scope and Closures

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

Javascript singleton: access outer attribute from inner function

// 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.

javascript singleton question

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
}
}

Categories

Resources