Using the "new" in javascript

I follow an example using require.js and backbone.js. In this example, the model does not use new when returned. In my code I have to use new , otherwise I get an error message:

 Uncaught TypeError: Object function (){a.apply(this,arguments)} has no method 'toJSON' 

Does not work:

 define([ 'underscore', 'backbone' ], function(_, Backbone) { var personModel = Backbone.Model.extend({ defaults: { conversations: 'No Conversations' }, initialize: function(){ } }); return personModel; }); 

Works:

 define([ 'underscore', 'backbone' ], function(_, Backbone) { var personModel = Backbone.Model.extend({ defaults: { conversations: 'No Conversations' }, initialize: function(){ } }); return new personModel; }); 

Does anyone know why?

+4
source share
2 answers

Backbone.Model.extend returns a constructor function - not an actual object. The constructor is not an object (and therefore will not have any properties) until it is created using new (as in your second example). This means that toJSON also unavailable, and you get the error you see.

When you are ready to create a new personModel , you can do it something like this (I will assume that the module described above was defined as "Face"):

 define("main", ["Person"], function (Person) { var me = new Person({ conversations: ['Hello, world']}); }); 
+4
source

Just for a more detailed explanation, whenever you do something new in JS, the object gets the __proto link and therefore access to the variables and prototype methods is a good practice when inheritance is desired.

To illustrate:

 function Animal(name) { this.name = name } Animal.prototype = { canWalk: true, sit: function() { this.canWalk = false } } var incompleteAnimal = Animal('cat'); alert (incompleteAnimal.canWalk) //error undefined variable var completeAnimal = new Animal('cat') alert (completeAnimal.canWalk); //true 

Only when you do a new will do you gain access to the canWalk variable and sit functions

+1
source

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


All Articles