Why use Ext.apply in initComponent

Oliver Watkins picture Oliver Watkins · Jun 25, 2014 · Viewed 8.6k times · Source

A lot of code examples use Ext.apply when setting properties on a component in the initComponent method.

Example :

    initComponent: function(){
        Ext.apply(this, {
            items: {
                xtype: 'button'
            }
    })},

My question is, what is the difference in doing it that way, compared to doing it this way :

    initComponent: function(){
        this.items = {
            xtype: 'button'
        }
    }

For me it seems more readable that way. But am I missing something that I get from Ext.apply?

Answer

sra picture sra · Jun 25, 2014

Ext.apply() is used to simplify the copying of many properties from a source to a target object (most of the time the source and target objects have different sets of properties) and it can in addition be used to apply default values (third argument).

Note that it will not make deep clones! Meaning if you have a array or a object as property value it will apply the reference!

There is also a applyIf() which only copies properties that do not already exist in the target object. In some cases both implementations have also the benefit of dropping the reference of the copied object.

Note: Your second way won't work because you are missing this.