2

I've been working through codeschool.com's tutorial on backbone.js And submitted:

var AppRouter = new Backbone.Router.extend({
  //code
});
$(function(){ AppRouter.start() });

and it gave the following error message:

TypeError: 'undefined' is not a function (evaluating 'AppRouter.start()') :28 :14

but adding a single parentheses solved the problem

var AppRouter = new (Backbone.Router.extend({
  //code
}));

I feel like it should have still worked before... What was happening when there was one less parentheses?

Sudipta
  • 4,773
  • 2
  • 27
  • 42
Paul Nogas
  • 309
  • 3
  • 16

2 Answers2

3

It was using Backbone.Router.extend as the constructor (with the parentheses going as arguments to the constructor, not the result of the Backbone.Router.extend call (where the call to Backbone.Router.extend returns a function to be used as a constructor). For example, compare:

function Test()
{   return function () { this.a = 2; };
}

console.log(new Test()); // function () { this.a = 2; }
console.log(new (Test())); // { a: 2 }
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
1

Answered another way, you need to be working with an instance of Backbone.Router, which you can first extend with your own router. Such as:

var AppRouter = Backbone.Router.extend({
    routes: {
        // code
    }
});

var router = new AppRouter();
Backbone.history.start();

The code in your example is evaluating the extend call first, then creating an instance with the return value. The end result is the same, but could be a bit misleading if you don't know the parentheses are causing the evaluation to take place.

Pappa
  • 1,593
  • 14
  • 20