Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.initialize(arguments) vs this.initialize.apply(this, arguments): what's the difference?

If you have a look at Backbone.js's source code, you'll see multiple uses of this pattern:

  this.initialize.apply(this, arguments);

For example, here:

  var Router = Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

Why not just write this.initialize(arguments) instead?

like image 272
TheFooProgrammer Avatar asked Mar 03 '13 06:03

TheFooProgrammer


1 Answers

this.initialize.apply(this, arguments)

Works like this:

this.initialize(arguments[0], arguments[1], arguments[2], ...)

Each item in arguments is passed as a parameter to initialize()

Which is very different from just:

this.initialize(arguments)

Pass arguments as the first and only parameter to initialize()

In other words, if the function expects an array as the first parameter, use this.initialize(arguments), otherwise use .apply().

like image 65
Ja͢ck Avatar answered Oct 15 '22 03:10

Ja͢ck