1

我有一个基本观点V

V = Backbone.View.extend({   
  initialize: function() {
    console.log(this.options.z);
    console.log(this.options.q);   
  }
});

扩展VV,它设置属性的值 ( q: 234):

VV = V.extend({q:234});

V进一步专门用于VV

new VV({z: 123})

​ 问题是基类型无法访问q,我该怎么做呢?q在这个例子中,我试图理解这个继承系统, z就像要在子类中定义的虚拟/抽象值一样。

http://jsfiddle.net/maxl/G8cab/

4

1 回答 1

0

当你这样说时:

VV = V.extend({q: 234});

您正在创建VV的“子类”V将具有额外的q属性。“类”定义的属性与View#initialize.

如果它说“创建视图的新实例”,文档可能会更好。

然后,当你在其单个参数中传递给视图的方法时new VV({z: 123}){z: 123}1.1.0之前的 Backbones 自动设置为构造函数的选项),你应该看起来更像这样:initializeoptionsthis.optionsqthis.qinitialize

initialize: function(options) {
  console.log(options.z);
  console.log(this.q);
}

另外,如果你这样做:

var VVV = VV.extend({q: 'pancakes'});

您将替换get和insideq实例的默认值。VVthis.q'pancakes'initialize

演示:http: //jsfiddle.net/ambiguous/eqBV2/

Using View#extend is like subclassing (or more accurately it creates a new prototypical instance) whereas new creates new objects (or copies of the prototypical instance). Of course, the class/instance language doesn't fit the reality of JavaScript so we have to be careful not to take the terminology too seriously.

于 2012-05-09T23:36:35.357 回答