JavaScript对象构造

JavaScript object construction

本文关键字:对象 JavaScript      更新时间:2023-09-26

通常ExtJS组件/对象是通过传递一个配置对象给它的构造函数来构造的,例如

    this.serviceFiltersPanel = new Ext.FormPanel({
        title: 'some title',
        layout:'anchor',
        buttonAlign: 'left',
        buttons: [
            {
                xtype: 'button',
                text: 'Click Me',
                handler: function () {
                    // How do I get a reference to the FormPanel 
                    // under construction here?
                });
            }
        ]
    });

是否有任何方法可以从按钮处理程序内部构造对FormPanel对象的引用?

var formPanel = new Ext.FormPanel({
    title: 'some title',
    layout:'anchor',
    buttonAlign: 'left',
    buttons: [
        {
            xtype: 'button',
            text: 'Click Me',
            handler: function () {
                // Q: How do I get a reference to the FormPanel 
                // under construction here?
                // A: use the formPanel variable.
            });
        }
    ]
});
this.serviceFiltersPanel = formPanel;

通常的方法是在构造函数中使用绑定,但是在extJS中在我读到这里的时候,似乎有很多方法可以做到这一点。

作为一个快速的常规js hack,你可以这样做,但它不是很干:

this.serviceFiltersPanel = new Ext.FormPanel({
    title: 'some title',
    layout:'anchor',
    buttonAlign: 'left',
    buttons: [
        {
        xtype: 'button',
        text: 'Click Me',
        handler: (function( obj ) {
                return function(){
                //obj.serviceFiltersPanel refers to the FormPanel instance created. This is the real function body,
                //the outer function is immediately executed.
                };
            })(this)
        }
    ]
});

可能有十几种方法可以做到这一点-这里是另一种(Ext JS 3.x)。

MyFormClass = Ext.extend( Ext.form.FormPanel, 
{
   /**
    * constructor (private) - 
    */
   constructor: function( params )  
   {
       var somePrivateVariable = true;      

    // A private event handler
    var _handleClickEvent = function( cmp ) {
        // I can reference somePrivateVariable
        // cmp is provided as a parameter
    }.createDelegate(this);   // force scope to instance of MyFormClass

    // Remainder of constructor
    argsForParent = {};
    argsForParent.collapsed = false;
    argsForParent.width = 320;
    argsForParent.items = [{
        xtype: 'button',
        click: _handleClickEvent
    }];
    argsForParent.listeners = [ ... ];
    // Declare my custom events
    this.addEvents( 'myCustomEvent' );
        MyFormClass.superclass.constructor.apply( this, [ argsForParent ]);
    } });   
Ext.reg( 'someXtype', MyFormClass );