繁体   English   中英

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

[英]Calling a private function of a module from a public method

此 Meteor 代码尝试调用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

您正在返回一个不引用 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();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM