为什么是this.callParent(arguments); 在ExtJS的构造函数开头调用?

Jae*_*Tee 15 extjs this

我注意到在我最近修改过的很多程序中,它们总是调用当前对象的父参数.我知道这是必要的,但对于为什么这是一种常见的做法并没有充分的理解.对于初级开发人员来说,有任何智慧......我应该知道这一点.

Joh*_*yHK 15

这是ExtJS用于在构造函数中支持类继承的机制.调用this.callParent(arguments)的构造函数调用多数民众赞成正在扩展的直接父类的构造函数.


Bha*_*hah 5

我不知道这个问题是关于哪个版本的.但就我的代码而言,在Ext JS 5中,callParent()- 调用当前方法的"父"方法.这是先前通过派生或覆盖覆盖的方法

试试这段代码.

MyApp.test :: LifecycleExample.js

Ext.define('MyApp.test.LifecycleExample', {
    extend: 'MyApp.test.TrialComponent',

    initComponent: function() {
        var me = this;

        me.width = 200;
        me.height = 100;
        me.html = {
            tag: 'div',
            html: 'X',
            style: {
                'float': 'right',
                'padding': '10px',
                'background-color': '#e00',
                'color': '#fff',
                'font-weight': 'bold'
            }
        };
        console.log("init is called before callParent()");

        me.myOwnProperty = [1, 2, 3, 4];

        me.callParent();

        console.log('1. initComponent');
    },

    beforeRender: function() {
        console.log('2. beforeRender');

        this.callParent(arguments);
    },

    onRender: function() {
        console.log('3. onRender');

        this.callParent(arguments);

        this.el.setStyle('background-color', '#ff0');
    },

    afterRender: function() {
        console.log('4. afterRender');

        this.callParent(arguments);

        this.el.down('div').on('click', this.myCallback, this);
    },

    beforeDestroy: function() {
        console.log('5. beforeDestroy');

        this.callParent(arguments);
    },

    onDestroy: function() {
        console.log('6. onDestroy');

        delete this.myOwnProperty;
        this.el.un('click', this.myCallback);

        this.callParent(arguments);
    },

    myCallback: function() {
        var me = this;
        Ext.Msg.confirm('Confirmation', 'Are you sure you want to close this panel?', function(btn) {
            if (btn === 'yes') {
                me.destroy();
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

MyApp.test :: TrialComponent.js(Ext.Component)

Ext.define('MyApp.test.TrialComponent', {
    extend: 'Ext.Component',

    constructor: function() {
        console.log('parent const');
        this.initComponent();
    },

    constructor: function(config) {
        console.log('parent const config' + config);
        this.initComponent();
    }
});
Run Code Online (Sandbox Code Playgroud)

浏览器控制台中的输出是:

parent const config[object Object]
init is called before callParent()
1. initComponent


callParent(args)调用当前方法的"父"方法.这是先前通过派生或覆盖覆盖的方法

参考是ext js api docs.

http://docs.sencha.com/extjs/5.0/apidocs/#!/api/Ext.Base-method-callParent