2016-04-26 100 views
1

此流星代碼嘗試調用send函數,但服務器報告錯誤「send is not defined」,並且如果將罪魁禍首行更改爲request.send,則得到Object沒有方法發送。從公共方法調用模塊的私有函數

爲什麼以及如何解決它?由於

request = (function() { 
    const paths = {logout: {method: 'GET'}} 
    const send =() => {some code} 

    return { 
    registerRequestAction: (path, func) => { 
     paths[path].action = func; 
    }, 
    invoke: (type) => { 
    paths[type].action(); 
    }  
    } 

    }()); 

request.registerRequestAction('logout',() => { 
send(); // send is not defined 
request.send(); // object has no method send 

}); 

request.invoke('logout'); // to fire it up 

回答

1

你沒有參考返回一個匿名對象發送方法:

// this isn't visible from the outside 
    const send =() => {some code} 

    // this is visible from the outside, 
    // but with no reference to send() 
    return { 
    registerRequestAction: (path, func) => { 
     paths[path].action = func; 
    }, 
    invoke: (type) => { 
    paths[type].action(); 
    }  
    } 

做這樣的事情應該解決您的問題:

return { 
    registerRequestAction: (path, func) => { 
      paths[path].action = func; 
    }, 
    invoke: (type) => { 
     paths[type].action(); 
    }, 
    // expose send to the outside 
    send: send 
} 

request.registerRequestAction('logout',() => { 
    request.send(); 
}); 
相關問題