了解 Backbone.View

发布于 2024-12-22 23:57:15 字数 276 浏览 0 评论 0原文

人们以多种方式使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凑诗 2024-12-29 23:57:15

都是一样的。

当您使用 Backbone.View.extend({}) 扩展一个类时,如您所见,您没有向您的类添加任何其他属性或方法。您向其传递一个空哈希 {} 作为参数。因此,Backbone.ViewBackbone.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 类的对象。它没有被扩展。
  • myView4myView3 相同

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 and Backbone.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 the new keyword, you're just talking about classes, whereas with the new 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() and new Backbone.View; are the same, just like new Backbone.View() and new Backbone.View.extend({}), for the reasons I wrote before.

About this fiddle (http://jsfiddle.net/C2Z34/):

  • myView1 is a class which extends View
  • myView2 (with parentesis as in my fiddle) is an object of a class extended of Backbone.View
  • myView3 is an object of Backbone.View class. It is not extended.
  • myView4 the same as myView3
孤独难免 2024-12-29 23:57:15

扩展创建一个子类。在您的示例中,您没有添加任何自定义代码,因此视图类的行为与原始主干视图完全相同。使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文