extend() using underscore vs. backbone [closed]

2020-05-20 10:06发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

I know backbone is somewhat depending on underscore and jquery. Is there difference between the two lines below?

app.notifications = _.extend({}, Backbone.Events);

AND

app.notifications  = Backbone.Events.extend({});

If they are NOT the same, how different?

回答1:

Backbone.Events.extend does not exist, so I will refer to Backbone.Model instead.

_.extend(target, mixin1, mixin2) is going to copy properties into the target object

Backbone.Model.extend is going to subclass Backbone.Model basically make a constructor (function) whose prototype has your provided properties. This will allow you to make instances of your new class

var Person = Backbone.Model.extend({name: 'yourName'});
var me = new Person();
alert(me.name);

while _.extend would fail

var Person = _.extend({name: 'yourName'}, Backbone.Model);
var me = new Person();  //error b/c Person is a regular object
alert(me.name);

In short Backbone.Model.extend creates a new constructor (function), while _.extend modifies an existing object;

var modified = {};
alert(modified === _.extend(modified, Backbone.Model)); //true
alert(modified === Backbone.Model.extend(modified)); //false