JavaScript object creation template

I read the article here:

http://javascriptweblog.wordpress.com/2010/03/16/five-ways-to-create-objects/

He talks about five ways to create objects. But my question is one of his ways (3):

myApp.Notepad = function(defaultFont) { var that = {}; that.writeable = true; that.font = defaultFont; that.setFont = function(theFont) { that.font = theFont; } return that; } myApp.notepad1 = myApp.Notepad('helvetica'); 

According to the author, we can use it when several instances are needed, we can use any template from 3 (above) to 5.

But as far as I know, we need to use the this , which reflects newly created instances and refers only to this instance. However, above, the author uses that object instead of this , as well as the new keyword above. How does this apply to instances of multiple objects? Is this the same as using this ?

+4
source share
2 answers

In your example, that is the new object created by this line:

 var that = {}; 

Then the function proceeds to adjust the properties of this object.

On the other hand, this used with a constructor function - when called using new new object is automatically created and passed to the function as this . The same example can be written as:

 myApp.Notepad = function(defaultFont) { this.writeable = true; this.font = defaultFont; this.setFont = function(theFont) { this.font = theFont; } } myApp.notepad1 = new myApp.Notepad('helvetica'); 
+4
source

One of the advantages of using the object literal constructor (your code), which has not yet been specified, is that when creating a new instance of the object, the new keyword is not required. Or, in other words, if you just forget to use the new keyword, your code will still work the way you plan, since you no longer rely on the use of the new keyword to provide the this scope of your newly created object in your constructor function ; An object that now takes care of you.

This is the approach that the YUI library (and Douglas Crockford) uses for designers.

Consider the following simple constructor:

 var Car = function(model){ this.model = model; }; 

If you were to call Car('Dodge Viper'); or even var MyCar = Car('Dodge Viper'); , this in the function actually refers to the global window object. So now the Model property is actually a global variable, which is probably not what it was intended to be.

 var Car = function(model) { var that = {}; that.model = model; return that; }; // Both work the same. var MamsCar = new Car("Mini Cooper"); // with 'new' var DadsCar = Car("Bugatti Veyron"); // without 'new' alert("Mam car is a " + MamsCar.model + " and dad car is a " + DadsCar.model); 
+2
source

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


All Articles