I’m trying to create something similar to static languages “static field”. Basically: counter property should be incremented every time the init function is called, but no matter on which instance. This is a sample code I’m using to test ( http://jsfiddle.net/HK8BY/2/ ) :
var Widget = {
counter: 0,
init: function () {
this.counter++;
console.log("init called: " + this.counter);
}
};
var t1 = Object.create(Widget);
var t2 = Object.create(Widget);
t1.init(); // should print: init called 1
t2.init(); // should print: init called 2
console.log(t1);
console.log(t2);
Currently when I console.log instanes, I see that both proto and instance contain counter property. I thought that with this approach, only proto will have it.
So how can I change it to have only counter in prototype?
http://jsfiddle.net/HK8BY/1/
So you just create IEFE (Immediately executed function expression) that returns the desired object. The
countervariable is available to the closure of that object’sinitfunction.