extend()使用下划线与骨干

时间:2012-10-28 01:13:01

标签: javascript jquery model-view-controller backbone.js underscore.js

我知道主干在某种程度上取决于下划线和jquery。下面两行之间有区别吗?

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

AND

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

如果他们相同,有多么不同?

1 个答案:

答案 0 :(得分:34)

Backbone.Events.extend不存在, 所以我将改为引用Backbone.Model。

_.extend(target, mixin1, mixin2)将属性复制到目标对象

Backbone.Model.extend将转到subclass Backbone.Model基本上构建一个构造函数(函数),其原型具有您提供的属性。这将允许您创建新类的实例

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

_.extend将失败

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

简而言之,Backbone.Model.extend创建一个新的构造函数(function),而_.extend修改一个现有的对象;

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