2016-04-26 69 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(); 
}); 
相关问题