[英]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.