I want to build a javascript function that maintains state. Here's a pattern that I've come up with, but something in the back of my mind tells me this is an anti-pattern.
function f() {
var state = 1;
f = function() {
return state++;
};
return f();
};
Is there anything wrong with this? If so, what's a better approach?
Well it's a matter of opinion what the best way is, but (although I know it works) I'm a little uncomfortable with having the function overwrite itself. A similar pattern that doesn't do that but still uses practically the same closure idea is this:
var f = function() {
var state = 1;
return function() {
return state++;
};
}();
Or here is another way:
function f() {
return f.state++;
}
f.state = 1;
Of course with the f.state method the advantage and disadvantage (depending on your needs) is that the .state property can be read and modified by other code.
Normally, you set a closure scope and return a function that has access to that scope. Every time that function is now called, the state will remain as long as that function exists. Example:
var statefulFunction = function() {
// set up closure scope
var state = 1;
// return function with access to the closure scope
return function() {
return state++;
};
}(); // immediately execute to return function with access to closure scope
var first = statefulFunction(); // first === 1
var second = statefulFunction(); // second === 2
Another pattern is to create a closure scope and return an object with methods that have access to that closure scope. Example:
var myStatefulObj = function() {
// set up closure scope
var state = 1;
// return object with methods to manipulate closure scope
return {
incr: function() {
state++;
},
decr: function() {
state--;
},
get: function() {
return state;
}
};
}();
myStatefulObj.incr();
var currState = myStatefulObj.get(); // currState === 2
myStatefulObj.decr();
currState = myStatefulObj.get(); // currState === 1
A better way to achieve this might be to use an Immediately-Invoked Function Expression (IIFE) to encapsulate your state.
var f = (function () {
var state = 1;
return function() {
return state++;
};
}());
console.log(f()); // 1
console.log(f()); // 2
Related
Given some javascript like this:
var doSomething = function() { return 1 };
doSomething.someProperty = "a";
How can I redefine the function so that, e.g., doSomething() returns 2, but without losing any additional properties defined on it?
I've found plenty of answers about this sort of thing for OOP, but I'm not using "new" here, just calling the function directly.
You can assign the properties from the original function to a new function:
Original Answer:
function redefineFunction(oldFn, newFn) {
Object.assign(newFn, oldFn);
return newFn;
}
// Original function and properties
var doSomething = function() { return 1 };
doSomething.someProperty = "a";
// Redefine
doSomething = redefineFunction(doSomething, function() { return 2 });
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
Simplified using Object.assign without needing a function:
var doSomething = function() {
return 1
};
doSomething.someProperty = "a";
// Redefine
doSomething = Object.assign(function() {return 2}, doSomething);
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
You could do something like this:
var doSomething = function() {
return doSomething.returnVal;
}
doSomething.returnVal = 1; // Without this, doSomething returns undefined
console.log(doSomething()); // <= 1
doSomething.returnVal = 2;
console.log(doSomething()); // <= 2
If you want to make some more dramatic change to the function (i.e. altering the algorithm that it runs rather than just a data value within it), then probably the best approach would be to create an entirely new function and copy the properties of your old function to it:
function copyProperties(source, destination) {
for (var property in source) {
destination[property] = source[property];
}
}
var doSomething = function() {
return 1;
}
doSomething.someProperty = "a";
var doSomethingElse = function() {
return 2;
}
copyProperties(doSomething, doSomethingElse);
console.log(doSomethingElse()); // <= 2
console.log(doSomethingElse.someProperty); // <= a
A strange problems about javascript prototype :
(function(w){
if(!w)
return;
var TestJS = function(){
};
TestJS.prototype = {
data:{},
initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
return this;
},
TestChildJS:{
initChild:function(){
console.log(TestJS);
console.log(TestJS.data);
console.log(new TestJS().data.val_name_1);
console.log(TestJS.data.val_name_1);
}
}
};
window.TestJS = new TestJS();
})(window);
why 'TestChildJS' can not get 'val_name_1'?
TestJS.initData();
console.log(TestJS.TestChildJS.initChild());
console pic
so I have to write my code like that:
(function(w){
if(!w)
return;
var TestJS = function(){
};
TestJS.prototype = {
data:{},
initData:function(){
this.data={
val_name_1 : 1,
val_name_2 : 2,
val_name_3 : "hello-3"
};
console.log(this.data);
this.TestChildJS.initParentData(this);
return this;
},
TestChildJS:{
parentData:{},
initParentData:function(parent){
this.parentData = parent.data;
return this;
},
initChild:function(){
console.log(this.parentData);
}
}
};
window.TestJS = new TestJS();
})(window);
How to use the first way can get the content of the second way?
why 'TestChildJS' can not get 'val_name_1'?
when:
TestJS.initData();
is run, it adds a data property to the TestJS object (the one assigned by window.TestJS = new TestJS()). That property isn't inherited by any other object.
When:
console.log(new TestJS().data.val_name_1);
is run, the object returned by new TestJS() has not had it's initData method called yet, so it doesn't have a data property and it doesn't inherit it from the constructor (because the property is directly on the constructor itself, not its prototype).
Note also that assigning a new object to this.data creates a property directly on the instance, so adding to this.data is modifying the instance's data object, not the one on the constructor's prototype.
The patterns in your code (especially the second one) seem unnecessarily convoluted.
It has to do with the scope of the IIFE. A variable declared inside a closure shadows any outer variable with the same name. Since after the IIFE executes you no longer have access to its scope, TempJS inside it will always be a function constructor -- not an instantiated object.
Consider this example:
var i;
var func = (function(){
i = 1;
return function() {
console.log(i)
};
})();
func(i); // 1
i = 2;
func(i); // 2
If I re-declare the i variable inside the closure, look what happens:
var i = 1;
var func = (function(){
var i = 1;
return function() {
console.log(i)
};
})();
func(i); // 1
i = 2;
func(i); // 1
So one solution to your problem would be to declare TestJS once before the IIFE.
var TestJS;
(function(w){
if(!w)
return;
TestJS = function(){
};
// ...
TestChildJS:{
initChild:function(){
console.log(TestJS.data.val_name_1);
}
// ...
window.TestJS = new TestJS();
})(window);
TestJS.initData();
console.log(TestJS.TestChildJS.initChild()); // 1
Notice that I removed console.log(new TestJS().data.val_name_1);. TestJS is no longer a constructor function, so that line will throw.
Another solution is to assign the empty function expression to window.TestJS inside the closure, instead of var TestJS. Doing so will not create a local TestJS name and will therefore prevent the ambiguity.
I am a bit new to javascript, i was just trying the below snippet:
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
s = _getUniqueID();
console.log(s); // 1
console.log(_getUniqueID()); // 2
I was under the impression that i would have to do s() to get 1 as the result and i was thinking that _getUniqueID() returns a function rather than execute the funtion inside it. Can somebody explain the exact execution of this function please ?
What you're seeing here is a combination of Javascript's notion of closure combined with the pattern of an immediately invoked function expression.
I'll try to illustrate what's happening as briefly as possible:
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}()); <-- The () after the closing } invokes this function immediately.
_getUniqueID is assigned the return value of this immediately invoked function expression. What gets returned from the IIFE is a function with a closure that includes that variable i. i becomes something like a private field owned by the function that returns i++ whenever it's invoked.
s = _getUniqueID();
Here the returned function (the one with the body return i++;) gets invoked and s is assigned the return value of 1.
Hope that helps. If you're new to Javascript, you should read the book "Javascript, the Good Parts". It will explain all of this in more detail.
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
s = _getUniqueID();
console.log(s); // 1
console.log(_getUniqueID()); // 1
when you do () it calls the function,
a- makes function recognize i as global for this function.
b- assigns function to _getUniqueID
you do s = _getUniqueID();,
a - it assigns s with return value of function in _getUniqueID that is 1 and makes i as 2
when you do _getUniqueID() again it will call the return function again
a- return 2 as the value and
b makes value of i as 3.
This is a pattern used in Javascript to encapsulate variables. The following functions equivalently:
var i = 1;
function increment() {
return i ++;
}
function getUniqueId() {
return increment();
}
But to avoid polluting the global scope with 3 names (i, increment and getUniqueId), you need to understand the following steps to refactor the above. What happens first is that the increment() function is declared locally, so it can make use of the local scope of the getUniqueId() function:
function getUniqueId() {
var i = 0;
var increment = function() {
return i ++;
};
return increment();
}
Now the increment function can be anonymized:
function getUniqueId() {
var i = 0;
return function() {
return i ++;
}();
}
Now the outer function declaration is rewritten as a local variable declaration, which, again, avoids polluting the global scope:
var getUniqueId = function() {
var i = 0;
return (function() {
return i ++;
})();
}
You need the parentheses to have the function declaration act as an inline expression the call operator (() can operate on.
As the execution order of the inner and the outer function now no longer make a difference (i.e. getting the inner generator function and calling it, or generate the number and returning that) you can rewrite the above as
var getUniqueId = (function() {
var i = 0;
return function() {
return i ++;
};
})();
The pattern is more or less modeled after Crockford's private pattern
_getUniqueID = (function () {
var i = 1;
return function () {
return i++;
};
}());
console.log(_getUniqueID()); // 1 , this surprised me initially , I was expecting a function definition to be printed or rather _getUniqueID()() to be called in this fashion for 1 to be printed
So the above snippet of code was really confusing me because I was't understanding that the above script works in the following manner, by the time the IFFE executes _getUniqueID is essentially just the following:
_getUniqueID = function () {
i = 1
return i++;
};
and hence,
_getUniqueID() // prints 1.
prints 1.
Note: please note that I understand how closures and IFFE's work.
Is it possible, while creating an instance of an object, to check during the instantiation itself the type of the parameter passed to the constructor, and set one of the object's variable accordingly?
This is what I'm trying to do:
function Test(num1) {
this.num1 = num1;
this.isValidNumber = (function() {
console.log(this.num1); // logs "undefined" upon instantiation
if (isNaN(this.num1)) {
return false;
} else {
return true;
}
}());
}
var testObj = new Test(5);
I want isValidNumber's value to be true or false according to the parameter passed to the constructor.
Your IIFE (Immediately-Invoked Function Expression) creates a new context, which means this doesn't point to your constructor anymore but to the Window object (unless you're using strict mode which would make it undefined). One possible solution is to execute this function with the right context:
this.isValidNumber = function() {
if (isNaN(this.num1)) {
return false;
} else {
return true;
}
}.call(this);
The much simpler solution is obviously:
function Test(num1) {
this.num1 = num1;
this.isValidNumber = !isNaN(this.num1);
}
First of all, the code could (and probably should) be rewritten the following way:
function Test(num1) {
this.num1 = num1;
console.log(this.num1);
this.isValidNumber = !isNaN(this.num1);
}
As for the reason why your code is not working as expected – your self invoking function has its own this parameter which is unrelated to the this parameter within your constructor.
In this case the this parameter of your self invoking function references the global object. (In strict mode it would've been undefined)
If you really need to reference the this parameter of a containing function then there are several ways to achieve this, the simplest of which being:
function Test(num1) {
this.num1 = num1;
var self = this;
this.isValidNumber = (function() {
console.log(self.num1);
return !isNaN(self.num1));
}());
}
In your particular case you don't even need to capture it, and this would also achieve the same effect:
function Test(num1) {
this.num1 = num1;
this.isValidNumber = (function() {
console.log(num1);
return !isNaN(num1));
}());
}
But again, the self invoking function is simply not required here.
This in the inner function no longer references the parent object. A common way of storing the object reference is to create a 'self' variable and assign this to it when it's in the correct scope
function Test(num1) {
var self = this;
this.num1 = num1;
this.isValidNumber = (function() {
console.log(self.num1);
if (isNaN(self.num1)) {
return false;
} else {
return true;
}
}());
}
var testObj = new Test(5);
When we are creating a method inside a closure it becomes private to that closure and can't be accessed until we expose it in some way.
How can it be exposed?
You can return a reference to it...
var a = function() {
var b = function() {
// I'm private!
alert('go away!');
};
return {
b: b // Not anymore!
};
};
See it on jsFiddle.
You could also bind it to the window object. But I prefer the method above, otherwise you are exposing it via a global variable (being a property of the window object).
You need to pass it to the outside in some manner.
Example: http://jsfiddle.net/patrick_dw/T9vnn/1/
function someFunc() {
var privateFunc = function() {
alert('expose me!');
}
// Method 1: Directly assign it to an outer scope
window.exposed = privateFunc;
// Method 2: pass it out as a function argument
someOuterFunction( privateFunc );
// Method 3: return it
return privateFunc;
}
someFunc()(); // alerts "expose me!"
function someOuterFunction( fn ) {
fn(); // alerts "expose me!"
}
window.exposed(); // alerts "expose me!"
You expose functions or properties of a closure by internally declaring them in this scope (which can change depending on invocation).
function example(val) {
var value = val;
this.getVal = function() {
return value;
}
this.setVal = function(v) {
value = v;
}
}
var ex = new example(2);
ex.getVal(); // == 2
ex.setVal(4); // == null
ex.getVal(); // == 4
Methods declared in this can access variables declared using var, but not the other way 'round.
function example(val) {
var value = val;
var double = function(v) {
return 2 * v;
}
this.getDouble = function() {
return double(value);
}
}
var ex = new example(2);
ex.getDouble(); // == 4
The function closes over the scope. What you want to do is to return a reference to a function that has access to the scope you require so you can invoke it at a later point.
If you need to create a function that calls a specific method at some later point,
var ex = new example(2);
var delayed_call = function() {
return(ex.getDouble()); // == 4, when called
}
setTimeout(delayed_call, 1000);
If scoping is an issue,
var ex = new example(2);
var delayed_call = (function(ex_ref) {
return function() {
return(ex_ref.getDouble()); // == 4, when called
}
})(ex); // create a new scope and capture a reference to ex as ex_ref
setTimeout(delayed_call, 1000);
You can inline most of this with the less readable example of,
setTimeout((function(ex_ref) {
return function() {
return(ex_ref.getDouble()); // == 4, when called
})(new example(2)))
, 1000
);
setTimeout is just a convenient way of demonstrating execution in new scope.
var ex = new example(2);
var delayed_call = function() {
return(ex.getDouble());
}
delayed_call(); // == 4
For performance purposes you can invoke it this way:
var a = (function(){
function _a(){}
_a.prototype = (function(){
var _test = function(){ console.log("test"); };
return {
test: _test
}
}());
return new _a();
}());
// usage
var x = a;
x.test(); // "test"