簡體   English   中英

ExpressJS和CoffeeScript類的繼承

[英]ExpressJS and CoffeeScript class inheritance

使用CoffeeScript我可以擴展節點的http.Server類:

{Server} = require 'http'
class MyServer extends Server
  foo: 'bar'
myserver = new MyServer
console.log myserver.foo # 'bar'

class MyServer2 extends MyServer
  constructor: -> super()
myserver2 = new MyServer2
myserver.listen 3000

如果我正確理解了這篇文章 ,可以express擴展的connect ,進而擴展http.Server 但是以下內容存在一些繼承問題:

Express = require 'express'
class MyApp extends Express
  foo: 'bar'
myapp = new MyApp
console.log myapp.foo # undefined

class MyApp2 extends MyApp
  constructor: -> super()
myapp2 = new MyApp2
console.log myapp2 # {}
myapp2.listen 3000 # throws TypeError

調用listen ,它將引發以下錯誤,因為myapp2是一個空對象{}並且沒有listen方法:

TypeError: Object #<MyApp2> has no method 'listen'

如何使用CoffeeScript以面向對象的方式使用express

是的,您完全可以做到。 只需刪除那些()

express = require 'express'
class MyApp extends express
myapp = new MyApp
myapp.listen 3000

express現在表示一個類,因此也許應該改成Express ,以遵守CoffeeScript的准則。 您會看到, express()返回的是http.Server的后代實例,而不是后代類,因此您嘗試擴展服務器實例。 CoffeeScript允許直接使用JS原型,而這正是您不經意間所做的。 因此,前兩行應如下所示:

Express = require 'express'
class MyApp extends Express

您不能從express或server擴展,因為它是一個函數而不是一個類。 您可以使用以下方法進行測試:

console.log(typeof express);

暫無
暫無

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

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