简体   繁体   English

node.js括号语法

[英]node.js bracket syntax

I am trying to understand some code used to make a Node.js dispatcher but I can't understand one line. 我试图理解一些用于制作Node.js调度程序的代码,但我听不懂一行。 Maybe my JavaScript gap . 也许我的JavaScript差距。 . . I commented the code with my doubts. 我对代码充满怀疑。

var HttpDispatcher = function() {
  this.listeners = { get: [ ], post: [ ] };
}

HttpDispatcher.prototype.on = function(method, url, cb) {
  this.listeners[method].push({
    cb: cb,
    url: url
  });
}

HttpDispatcher.prototype.onGet = function(url, cb) {
  this.on('get', url, cb);
}

HttpDispatcher.prototype.onPost = function(url, cb) {
  this.on('post', url, cb);
}

HttpDispatcher.prototype.dispatch = function(req, res) {
  var parsedUrl = require('url').parse(req.url, true);
  var method = req.method.toLowerCase();
  this.listener[method][parsedUrl.pathname](req, res); // i don't understand this line
}

Why do we refer to this.listener as a bidimensional array? 为什么我们将this.listener称为二维数组? We defined listeners like an array of object! 我们将侦听器定义为对象数组! and why do we pass parameters? 为什么我们要传递参数?

It's not a bidimensional array, its bracket notation being used to access a nested property of an object. 它不是二维数组,其括号表示法用于访问对象的嵌套属性。

this.listener[method][parsedUrl.pathname](req, res)
|-------------------||------------------||--------|
 ^object property of  ^nested function    ^ invocation of the function 
  the listener object  of the listener
  where the property   object where the
  key is the method    property key is
                       the path name

Properties of nested objects can be accessed by chaining dot and/or bracket references together. 嵌套对象的属性可以通过将点和/或方括号引用链接在一起来访问。 The following are all equivalent: 以下都是等效的:

object.baz.foo.bar;
object["baz"]["foo"]["bar"];
object["baz"].foo["bar"];

Check this for more details. 检查以获取更多详细信息。

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

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