With CoffeeScript
I can extend node's http.Server
class:
{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
If I have correctly understood this post , express
extends connect
which in turn extends http.Server
. But the following have some inheritance problems:
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
When listen
is called it throws the following error because myapp2
is an empty object {}
and doesn't have the listen
method:
TypeError: Object #<MyApp2> has no method 'listen'
How can I use express
in an Object Oriented Way with CoffeeScript
?
Yes, you can totally do it. Just remove those ()
:
express = require 'express'
class MyApp extends express
myapp = new MyApp
myapp.listen 3000
express
now represents a class, so maybe you should call it Express
instead, to stick with CoffeeScript's guidelines. You see, express()
returns you an instance of a descendant of http.Server
, not a descendant class, so you were trying to extend a server instance. CoffeeScript allows direct usage of JS prototypes, and that's what you accidentally did. So, the first two lines should look like this:
Express = require 'express'
class MyApp extends Express
You can't extend from express or server, because it's a function not a class. You can test this by using:
console.log(typeof express);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.