Using it or new in JS?

I have 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 has just been declared once. Then I use "control" everywhere in my code ...

I was wondering if control.doSomethingElse () is slower?

After all, what needs to be done and / or the fastest code in these examples?

Thanks!

+5
source share
2 answers

The first is false - an object should never use the variable name by which it is known externally. Other code may modify this variable, indicating something else, violating this code.

The third one is also wrong - when you call Control() without a new assignment, this.foo inside will bind to the global object (except for strict mode, where there is no implicit this on the bare function, calls this.doSomethingElse try to connect to undefined , causing a runtime error) .

This leaves only the second, but ultimately it is a matter of correctness, not performance.

+3
source

Do not define methods in the constructor - this means defining them every time an instance is created. Use Control.prototype.foo = function() {} instead. Also, you do not need to return this if you are using the new operator β€” the whole point of the new operator.

Recommended Approach:

 function MyClass(param1) { // Here we're changing the specific instance of an object this.property1 = param1; } // Prototype will be shared with all instances of the object // any modifications to prototype WILL be shared by all instances MyClass.prototype.printProperty1 = function() { console.log(this.property1); } var instance = new MyClass("Hello world!"); instance.printProperty1(); // Prints hello world 

To understand this code, you need to understand the javascript prototype-based inheritance model. When you create an instance of MyClass, you get a new object that inherits any properties that are present in MyClass.prototype . More on this


I also wonder:

A function is a controller and has just been declared once.

If you do not use this several times, you do not need to create something like a class. You can do this instead:

 var control = {doSomething:function() { ... }}; 

I assume that you are used to Java, where everything should be a class, regardless of whether it makes sense or not. Javascript is different, you can also create individual objects or functions as needed.

+2
source

Source: https://habr.com/ru/post/1238731/


All Articles