-2
var createworker = function() {

    var workcount;
    var input;
    (function() {
        workcount = 0;
        console.log("hello");
    }());
    var task1 = function() {
        workcount += 1;
        console.log("task1" + workcount);
    };
    var task2 = function(a) {
        workcount += 1;
        input = a;
        console.log("task2" + workcount + "variable" + a);
    };
    var task3 = function() {
        console.log(input);
    };

    return {
        job1: task1,
        job2: task2,
        job3: task3
    };
}

var worker = new createworker();
worker.job1();
worker.job2(2);
worker.job3();

var worker1 = createworker();
worker1.job1();
worker1.job2(2);
worker1.job3();

Both work same. Then why to use new and when to use it?

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
Anik Saha
  • 3,521
  • 1
  • 19
  • 34

1 Answers1

2

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:

  1. Creates a new object backed by the object the constructor function's prototype property points ot
  2. Calls the constructor function with this referring to that new object
  3. 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
};
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639