2010-02-04 133 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();