From the MDN docs on the new operator
:
The object returned by the constructor function becomes the result of
the whole new expression*. If the constructor function doesn't
explicitly return an object, the object created in step 1 is used
instead. (Normally constructors don't return a value, but they can
choose to do so if they want to override the normal object creation
process.)
*Emphasis mine
What you're doing here is overriding the default behavior of new
. Your code equates to the following:
var abc = function()
{
this.c = 1;
return this.c;
};
abc.c; // undefined.
Even though you've declared this.c
your function()
hasn't actually been executed at this stage, so this.c
is still undefined.
Then, you new
abc
with the traditional approach, so:
var xyz = new function() {
this.c = 1;
return this.c;
};
xyz.c === 1; // Works, because you've new'd the function correctly
Assuming you're trying to implement a counter object-oriented style function, you could try something like:
function setup()
{
this.count = 0;
this.increment = function() {
this.count++;
}
};
var counter = new setup();
counter.increment();
counter.increment();
console.log(counter.count); // 2
var counter2 = new setup();
counter2.increment();
console.log(counter2.count); // 1
Or using prototypal inheritance:
function setup() {}
setup.prototype.count = 0;
setup.prototype.increment = function() {
this.count++;
};
Although naming convention would dictate you should call your class something like:
function Counter() {
this.value = 0;
this.increment = function();
}
var first = new Counter();