Reputation: 409
I have found the simple solution here using closure
from @Xotic750
But, Is it possible to run function without round brackets? E.G.:
var increment = new Increment()
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
Every function run I have got the function as [object Object]
in console.log
instead of value
:
var Increment = (function(n) {
return function() {
n += 1;
return n;
}
}(0));
var increment = new Increment();
console.log('value: ' + increment) // value: [object Object]
console.log('value: ' + increment) // value: [object Object]
console.log('value: ' + increment) // value: [object Object]
Upvotes: 0
Views: 75
Reputation: 350477
As you are printing the increment
instances, there is a toString
conversion happening. You could use that to perform the increment:
var Increment = (function(n) {
var f = function() {}; // Only serves as constructor
f.prototype.toString = function() {
n += 1;
return n;
}
return f
}(0));
var increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
Be aware, the counter is kinda global. If you want the counter to be separate and restart from 0 for each instance, then use this
:
var Increment = (function(n) {
var f = function() {
this.n = 0;
};
f.prototype.toString = function() {
this.n += 1;
return this.n;
}
return f
}(0));
var increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
increment = new Increment();
console.log('value: ' + increment) // value: 1
console.log('value: ' + increment) // value: 2
console.log('value: ' + increment) // value: 3
Upvotes: 2
Reputation: 22474
Is it possible to run function without round brackets
Yes, you can do that using a getter, here is an example:
class Cls {
constructor() {
this.value = 0;
}
get increment() {
return this.value++
}
}
const cls = new Cls()
console.log('value: ' + cls.increment)
console.log('value: ' + cls.increment)
console.log('value: ' + cls.increment)
Upvotes: 1
Reputation: 2706
You are creating an object of the function Increment
by using the new
keyword. In your case, you would simply want to call the Increment
function as so:
console.log('value: ' + Increment());
console.log('value: ' + Increment());
console.log('value: ' + Increment());
See this link on Closures for a more detailed explanation as to how they work.
Upvotes: 1