Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this or new in JS?

I've got 3 codes :

var control = new Control();

function Control() {

   this.doSomethingElse = function() {...}
   this.doSomething = function () {
       control.doSomethingElse();
   }

}

Or

var control = new Control();

function Control() {
   var self = this;

   this.doSomethingElse = function() {...}
   this.doSomething = function () {
       self.doSomethingElse();
   }
}

Or

var control = Control();

function Control() {
   var self = this;

   this.doSomethingElse = function() {...}
   this.doSomething = function () {
       self.doSomethingElse();
   }

  return self;
}

Important : The function is a controller, and just declared once. Then I'm using "control" everywhere in my code...

I was wondering if the control.doSomethingElse() was slow ?

In the end, what is the right thing to do and/or the fastest code in those exemple ?

Thanks !

like image 278
alexino2 Avatar asked Dec 19 '15 20:12

alexino2


1 Answers

The first is wrong - an object should never internally use the variable name by which it is known outside. Other code could change that variable to point to something else, breaking this code.

The third is also wrong - when calling Control() without new the assignments to this.foo inside will end up getting attached to the global object (except in strict mode, where there's no implicit this on bare function calls, so the assignment to this.doSomethingElse tries to attach to undefined, causing a runtime error).

That only leaves the second as appropriate, but ultimately it's a question of correctness, not performance.

like image 173
Alnitak Avatar answered Sep 22 '22 15:09

Alnitak