2

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?

Community
  • 1
  • 1
Jorge Barata
  • 2,227
  • 1
  • 20
  • 26

2 Answers2

0

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
Utgarda
  • 686
  • 4
  • 23
0

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);

Richard Torcato
  • 2,504
  • 25
  • 26