2016-03-06 62 views
1
var Dashboard=function(){ 
this.__construct=function(){ 

    console.log('Dashboard is Created'); 
    template=new Template(); 
    events=new Event(); 
    load_todo(); 


    //console.log(Template.todo({todo_id:1,content:"This is life"})); 
}; 
//----------------------------------- 
var load_todo=function(){ 
    console.log('load todo is called'); 
    $.get("api/get_todo",function(o){ 
     $("#list_todo").html(); 

     },'json'); 
};}; 

我無法調用load_todo()函數,誰能告訴錯誤是這段代碼。語法錯了還是什麼?javascript私人函數調用錯誤

+0

你會得到什麼錯誤?你在哪裏調用'__construct',你是否在初始化'load_todo'變量之前調用它? – Bergi

+0

您可能會希望使用函數聲明而不是函數表達式,並將'var'用於'template'和'events'變量。 – Bergi

+0

在var load_todo行之前創建了Dashboard對象嗎? – VahagnNikoghosian

回答

1

您必須首先創建一個對象,然後調用方法:

var Dashboard=function(){ 
this.__construct=function(){ 

    console.log('Dashboard is Created'); 
    template=new Template(); 
    events=new Event(); 
    load_todo(); 


    //console.log(Template.todo({todo_id:1,content:"This is life"})); 
}; 



//----------------------------------- 
var load_todo=function(){ 
    console.log('load todo is called'); 
    $.get("api/get_todo",function(o){ 
     $("#list_todo").html(); 

     },'json'); 
};}; 


//You have to call the construct function 
var dashboard = new Dashboard().__construct(); 

現在,如果你想保持你的函數私人那麼你可以做類似下面的例子:

function Dashboard(){//begin dashboard constructor 

    __construct(); 

function __construct(){ 

    console.log('Dashboard is Created'); 
    template=new Template(); 
    events=new Event(); 
    load_todo(); 

    //console.log(Template.todo({todo_id:1,content:"This is life"})); 

} 


function load_todo(){ 
    console.log('load todo is called');  

    $.get("api/get_todo",function(o){ 
     $("#list_todo").html(); 

    },'json'); 


} 

}//end dashboard constructor 


//create a new Dashboard object instance 
var dashboard = new Dashboard(); 

//This will not work because load_todo will be undefined. 
console.log(dashboard.load_todo());