Andrew Boes
Andrew Boes

Reputation: 2043

Using "new" in javascript

I'm following an example on how to use require.js and backbone.js. In the example, the model does not use new when it returns. In my code I have to use new otherwise I get an error:

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

Doesn't 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;
});

Anybody know why?

Upvotes: 4

Views: 1885

Answers (2)

rjz
rjz

Reputation: 16510

Backbone.Model.extend returns a constructor function--not an actual object. The constructor isn't an object (and consequently won't have any properties) until it's been instantiated using new (as in your second example). That means that toJSON isn't available, either, and you end up with the error you're seeing.

When you're ready to actually create a new personModel, you might do it something like this (I'll assume that the module you described above has been defined as "Person"):

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

Upvotes: 4

Vijay Agrawal
Vijay Agrawal

Reputation: 3821

Just for a more detailed explanation, whenever you do a new in JS, the object gets the __proto reference and hence access to the prototype variables and methods - this is good practice whenever 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 you get access to the canWalk variable and sit function

Upvotes: 1

Related Questions