0

アプリケーションのコードをレビューしていました。包括的に理解できない次のコードに出くわしました。

 define(['av'], function (av) {
     av.Application.BaseView = function (options) {
      //add non-shared methods/properties here --------------------- 1)

    };
    _.extend(av.Application.BaseView.prototype, Backbone.View.prototype, {
      // add shared methods/properties here ------------------------ 2)
    });
   av.Application.BaseView.extend = Backbone.View.extend;

});

コメント1の後に追加されたメソッド/プロパティが共有されておらず、コメント2の後に子インスタンス間で共有されているのはなぜですか?

4

1 に答える 1

2

The first block of code defines a constructor function, which is called every time you new up a view. In that function you can create public properties with the syntax:

this.foo = "bar";

This initialization code runs every time a view is initialized, and it attaches the properties to the instance of the view. Instance properties are not shared.

The second block of code extends the constructor function's prototype, first with all the properties of Backbone.View, and then with the properties defined in the block. Prototype properties are shared between all instances of the function, or "class", if you wish.

What that code essentially does is create a new function, and then enhance it with Backbone.View's properties. Because the Backbone.View's own constructor function is never called (at least in the code you posted), it means that this class wouldn't quite work like a normal Backbone View. For instance a model or id property passed to a constructor would not be copied to the instance automatically, as they normally would:

var view = new av.Application.BaseView({model:model});
console.log(view.model); //-> undefined

Backbone also supports overriding the constructor function more cleanly by setting a constructor attribute in the class definition:

av.Application.BaseView = Backbone.View.extend({

    //override the constructor function
    constructor: function(options) {

        //this property is not shared between instances
        this.foo = 'bar';

        //call Backbone's own constructor, so we get all the default behavior
        Backbone.View.prototype.constructor.apply(this, arguments);
    },

    //this property is attached to the prototype, and is shared
    baz: 'qux'
});
于 2013-01-16T15:32:52.707 に答える