2010-02-04 113 views
0

虽然我试图这样JavaScript错误创建对象

new Ext.TitleCheckbox() 

我得到“不是构造函数错误”创建对象

我的对象是

Ext.TitleCheckbox = { 

    checked:false, 
    constructor : function() { 
    }, 
    getHtml : function (config) { 
     var prop = (!config.checked)?'checkbox-checked':'checkbox-unchecked'; 
     var html = config.title+'<div class="'+prop+'" onclick="Ext.TitleCheckbox.toggleCheck(this)">&#160;</div>'; 

     return html; 
    }, 

    toggleCheck : function (ele){ 
     if(ele.className == 'checkbox-checked') { 
      ele.className = 'checkbox-unchecked'; 
     } 
     else if(ele.className == 'checkbox-unchecked') { 
      ele.className = 'checkbox-checked'; 
     } 

    }, 

    setValue : function(v){ 
     this.value = v; 
    }, 

    getValue : function(){ 
     return this.value; 
    } 

}; 

什么错误在这里?

回答

3

Ext.TitleCheckbox不是函数,你不能对对象文字进行函数调用。

如果要使用new运算符,则应重新构造代码以使TitleCheckboxconstructor function

像这样的东西(assumming的Ext对象存在):

Ext.TitleCheckbox = function() { 
    // Constructor logic 
    this.checked = false; 
}; 

// Method implementations 
Ext.TitleCheckbox.prototype.getHtml = function (config) { 
    //... 
}; 

Ext.TitleCheckbox.prototype.toggleCheck = function (ele) { 
    //... 
}; 

Ext.TitleCheckbox.prototype.setValue = function (v) { 
    //... 
}; 

Ext.TitleCheckbox.prototype.getValue = function() { 
    //... 
}; 
0

见CMS的回答为什么。作为解决方法,如果你真的需要这样做,你可以通过继承来完成。在javascript构造函数继承对象(一个构造函数只是一个函数)。所以:

function MyCheckbox() {} ; /* all we really need is a function, 
          * it doesn't actually need to do anything ;-) 
          */ 

// now make the constructor above inherit from the object you desire: 

MyCheckbox.prototype = Ext.TitleCheckbox; 

// now create a new object: 

var x = new MyCheckbox();