簡體   English   中英

NODEJS中的Javascript方法鏈接

[英]Javascript Method Chaining in NODEJS

當您在javascript中鏈接方法時,是否會在初始對象上調用它? 還是先前方法的返回對象?

我問這個問題是因為在Node中我鏈接了.listen()

有用:

var http = require("http");

http.createServer(function (request, response) {
   response.writeHead(200, {
     'Content-Type': 'text/plain'
   });
   response.end('Hello World\n');
}).listen(8088);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

createServer之后調用listen()時,它不起作用:

http.createServer(function (request, response) {
   response.writeHead(200, {
     'Content-Type': 'text/plain'
   });
   response.end('Hello World\n');
})

http.listen(8088);

它說listen()不起作用。 為什么當我鏈接它時它會起作用?

因為http是與createServer創建的http.Server實例不同的模塊。 請參閱此處的文檔並嘗試使用console.log()變量,以查看在其上定義了哪些函數和屬性。

流利的接口通過返回您所調用的同一對象來工作(通過以return this結束該方法),因此您可以鏈接對該對象的調用(因此,使其成為“流利的”)。

https://en.wikipedia.org/wiki/Fluent_interface

就您而言,這與方法鏈接無關。 調用http.createServer返回一個不同於http的新對象,您可以在其上調用listen。

這是因為createServer返回http.Server的新實例。

Class: http.Server

此類從net.Server繼承,並且具有事件'listening' 更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM