从公共方法调用模块的私有函数

时间:2016-04-26 10:57:59

标签: javascript meteor

此Meteor代码尝试调用send函数,但服务器报告错误"发送未定义"如果我将罪魁祸首行改为request.send,我得到的对象没有方法发送。

为什么以及如何解决这个问题?感谢

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 个答案:

答案 0 :(得分:1)

您将返回匿名对象而不参考send方法:

  // 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();
});