使用下划线与骨干延伸()[关闭](extend() using underscore vs. bac

2019-08-02 01:05发布

我知道骨干在一定程度上取决于下划线和jQuery。 是否有下面的两条线之间的区别?

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

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

如果它们是一样的,有什么不同?

Answer 1:

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创建一个新构造(功能),而_.extend修改现有对象;

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


文章来源: extend() using underscore vs. backbone [closed]