简体   繁体   English

ExpressJS和CoffeeScript类的继承

[英]ExpressJS and CoffeeScript class inheritance

With CoffeeScript I can extend node's http.Server class: 使用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

If I have correctly understood this post , express extends connect which in turn extends http.Server . 如果我正确理解了这篇文章 ,可以express扩展的connect ,进而扩展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: 调用listen ,它将引发以下错误,因为myapp2是一个空对象{}并且没有listen方法:

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

How can I use express in an Object Oriented Way with CoffeeScript ? 如何使用CoffeeScript以面向对象的方式使用express

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. express现在表示一个类,因此也许应该改成Express ,以遵守CoffeeScript的准则。 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. 您会看到, express()返回的是http.Server的后代实例,而不是后代类,因此您尝试扩展服务器实例。 CoffeeScript allows direct usage of JS prototypes, and that's what you accidentally did. CoffeeScript允许直接使用JS原型,而这正是您不经意间所做的。 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. 您不能从express或server扩展,因为它是一个函数而不是一个类。 You can test this by using: 您可以使用以下方法进行测试:

console.log(typeof express);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM