简体   繁体   English

Node.js模块:引用同级函数的正确方法

[英]Node.js modules: correct way to refer to sibling functions

This is my current code: 这是我当前的代码:

var PermissionsChecker = {};

PermissionsChecker.check = function(id) {
  PermissionsChecker.getPermissions(id);
}

PermissionsChecker.getPermissions = function(id) {
  // do stuff
}

Two questions: 两个问题:

  1. Is this the right way to construct node.js functions? 这是构造node.js函数的正确方法吗?
  2. Is that line in .check the correct way to refer to a sibling function? .check的那行是引用同级函数的正确方法吗?

Thanks! 谢谢!

So long as the function is called with PermissionsChecker.check() , you can refer to the object with this . 只要使用PermissionsChecker.check()调用该函数,就可以使用this引用该对象。

CodePad . 键盘

What you've done above is called an object literal, but you could choose the prototypal way also (when you need to instantiate objects - OOP stuff). 上面做的事情称为对象文字,但是您也可以选择原型方式(当您需要实例化对象时-OOP的东西)。

You can call this inside to refer to another object property: 您可以在内部调用此名称以引用另一个对象属性:

PermissionsChecker.check = function(id) {
  this.getPermissions(id);
}

It's perfectly fine. 很好 Some notes: 一些注意事项:

  • Sibling function isn't really any standard term for methods of the same object. 兄弟功能实际上不是同一对象方法的任何标准术语。 Minor note, but could cause confusion. 小调,但可能引起混乱。
  • When a function is called as a method on some object, then the value of this inside that function refers to the object on which it was called. 当某个函数被作为某个对象的方法调用时,该函数内部的this值将引用该对象在其上被调用。 That is, calling check like this: 也就是说,这样调用check

     PermissionsChecker.check() 

    ...allows you to write the function like this: ...允许您编写如下函数:

     PermissionsChecker.check = function(id) { this.getPermissions(id); } 

    ...which is more succinct and probably more common. ...更简洁,可能更常见。

  • Nothing about your question is specific to node.js. 关于您的问题,没有什么是Node.js特有的。 This applies to JavaScript in the browser (or anywhere else), too. 这也适用于浏览器(或其他任何地方)中的JavaScript。

  • You could save some typing by rewriting your example like this: 您可以通过重写示例来节省一些输入:

     var PermissionsChecker = { check: function(id) { this.getPermissions(id); }, getPermissions: function(id) { // do stuff } }; 

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

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