了解 Backbone.View
人们以多种方式使用 Backbone.View,我有点困惑。我看到:
Backbone.View.extend({});
new Backbone.View.extend({});
new Backbone.View();
new Backbone.View;
前三个不同。最后两个是一样的。 (请参阅此处了解小提琴。)每种情况发生了什么?
People use Backbone.View
in many ways, and I'm kind of confused. I have seen:
Backbone.View.extend({});
new Backbone.View.extend({});
new Backbone.View();
new Backbone.View;
The first three are different. The last two are the same. (See here for a Fiddle.) What is happening in each case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
都是一样的。
当您使用
Backbone.View.extend({})
扩展一个类时,如您所见,您没有向您的类添加任何其他属性或方法。您向其传递一个空哈希{}
作为参数。因此,Backbone.View
和Backbone.View.extend({})
几乎是同一件事。关于之前的
new
关键字,它只是实例化一个新类。当您不使用new
关键字时,您只是在谈论类,而使用new
关键字时,您正在谈论同一个类的对象。括号不是义务。仅当您想将参数传递给其构造函数时才需要它,因此
new Backbone.View()
和new Backbone.View;
是相同的,就像new Backbone.View()
和new Backbone.View.extend({})
,原因我之前写过。关于这个小提琴(http://jsfiddle.net/C2Z34/):
myView1
是一个扩展视图的类myView2
(带有括号,如我的小提琴)是一个对象Backbone.View 的扩展类myView3
是 Backbone.View 类的对象。它没有被扩展。myView4
与myView3
相同It is all the same thing.
When you exetend a class using
Backbone.View.extend({})
, as you can see, you are not adding any aditional property or method to your class. You're passing it an empty hash{}
as argument. So,Backbone.View
andBackbone.View.extend({})
are pretty much the same thing.About the
new
keyword presence before, it just instanciate a new class. When you don't use thenew
keyword, you're just talking about classes, whereas with thenew
keyword, you are talking about an object of this very same class.Parentesis are not an obligation. It is only required if you want to pass arguments to its constructor, so
new Backbone.View()
andnew Backbone.View;
are the same, just likenew Backbone.View()
andnew Backbone.View.extend({})
, for the reasons I wrote before.About this fiddle (http://jsfiddle.net/C2Z34/):
myView1
is a class which extends ViewmyView2
(with parentesis as in my fiddle) is an object of a class extended of Backbone.ViewmyView3
is an object of Backbone.View class. It is not extended.myView4
the same asmyView3
扩展创建一个子类。在您的示例中,您没有添加任何自定义代码,因此视图类的行为与原始主干视图完全相同。使用 new 关键字,您可以调用类的构造函数,该函数返回视图的实例。
因此,如果您想在视图中使用自定义代码,例如。使用渲染函数可以扩展 BB 视图。然后,当您想要使用此视图时,您可以创建扩展视图的新实例。
Extend creates a subclass. In your examples you do not add any custom code so the viewclasses behave exactly like the original backbone views. With the new keyword you call the constructor function of your class which returns an instance of a view.
So if you want to have custom Code in a view eg. with a render function you extend BB view. Then when you want to use this view you create a new instance of your extended view.