[英]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: 两个问题:
.check
the correct way to refer to a sibling function? .check
的那行是引用同级函数的正确方法吗? Thanks! 谢谢!
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: 一些注意事项:
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.