What is the point of Ext.apply versus simply setting values on the target?

旧城冷巷雨未停 提交于 2019-12-05 18:02:34

问题


Using Ext.js or sencha, what is the point of doing the following:

Ext.apply(app.views, {
        contactsList: new app.views.ContactsList(),
        contactDetail: new app.views.ContactDetail(),
        contactForm: new app.views.ContactForm()
    });

As opposed to this standard javascript:

app.views.contactsList = new app.views.ContactsList();
app.views.contactDetail = new app.views.ContactDetail();
app.views.contactForm = new app.views.ContactForm();

Is there any difference?


回答1:


It's mostly there as a convenience method for code that is accepting an object as an argument, and needs to merge it. Merging objects is a common use case in JavaScript, and this type of helper is implemented by most frameworks. ($.extend in jQuery, Object.extend in Prototype, Object.append in MooTools, etc.)

In your case, there is little difference, other than offering a bit more readable code.




回答2:


Ext.apply is generally more convenient (and possibly more efficient if there are fewer activation chain lookups required, as in your example, though that's a minor point) . There is also a variant Ext.applyIf that only applies members from the source object that do not exist in the target object, which is even more useful as it saves you from a boatload of manual if() checks. That's really useful, for example, when applying defaults to a config object that may already have user or app-defined properties assigned.

A note to future readers who look at the accepted answer: Ext also has Ext.extend which actually means "inherit from" a class, as opposed to Ext.apply[If] which merely merges an object instance into another, or Ext.override which overrides (without subclassing) a class definition. Lots of options, depending on what you need.




回答3:


You need Ext.apply if you use Ajax requests to get the configurations from the server. Because Ajax responses are received later on, after the window is rendered. The second part of your code won't work.



来源:https://stackoverflow.com/questions/5268422/what-is-the-point-of-ext-apply-versus-simply-setting-values-on-the-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!