Both work same.
They reason they both work the same is that you're returning an object from createworker
. That overrides the work that new
did.
new
is used with constructor functions. It does this:
- Creates a new object backed by the object the constructor function's
prototype
property points ot
- Calls the constructor function with
this
referring to that new object
- In the normal case, the result of
new functionname
is a reference to the object that new
created. But, if the constructor function returns a non-null
object reference, the result of the new
expression is that object instead. It's that "but" that's happening in your createworker
example.
So your version of createworker
doesn't need new
, because of the way it's written.
And doing it that way is absolutely fine; in fact, there are people who always do it that way. If you wanted to use new
with createworker
, here's a version designed to be used that way (renamed CreateWorker
, because by convention constructor functions are capitalized):
var CreateWorker = function() {
var workcount;
var input;
(function() { // Side note: This function is pointless. Just move
workcount = 0; // <− this line
console.log("hello"); // <− and this one
}()); // ...out into the body of `createworker`/`CreateWorker`
// Note we assign to properties on `this`
this.job1 = function() {
workcount += 1;
console.log("task1" + workcount);
};
this.job2 = function(a) {
workcount += 1;
input = a;
console.log("task2" + workcount + "variable" + a);
};
this.job3 = function() {
console.log(input);
};
// Note we aren't returning anything
};