The underscore.js library provides an extend
method that does what you want. You can define functionality on any object, and then quite literally copy & paste all of the methods and attributes from that object to another.
Backbone's extend
methods on Views, Models, and Routers are a wrapper around underscore's extend
.
var MyMixin = {
foo: "bar",
sayFoo: function(){alert(this.foo);}
}
var MyView = Backbone.View.extend({
// ...
});
_.extend(MyView.prototype, MyMixin);
myView = new MyView();
myView.sayFoo(); //=> "bar"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…