0

我有一个 Coffeescript 子类Error。以下 CoffeeScript 脚本

class MyError extends Error
  constructor: (message, @cause) ->
    super message

myError = new MyError 'This is the error message!'

console.log myError instanceof MyError
console.log myError instanceof Error
console.log "'#{myError.message}'"
console.log myError.message == ''

显示

true
true
''
true

在 Node.js v0.10.20 下。

为什么message属性为myError空?

4

1 回答 1

2

明确设置@message作品

class MyError extends Error
  constructor: (@message,@cause)->
    Error.captureStackTrace(@,@)

coffee> ee=new MyError 'test'
{ message: 'test', cause: undefined }
coffee> "#{ee}"
'Error: test'
coffee> ee.message
'test'
coffee> ee instanceof MyError
true
coffee> ee instanceof Error
true
coffee> throw new MyError 'test'
Error: test
    at new MyError (repl:10:11)
...

super当另一个类建立时做得很好MyError

class OError extends MyError
   constructor: (msg)->
     super msg
     @name='OError'

下面显示了正确的消息,并且对于util.isError, is是正确的instanceof Error,但不是instanceof Error1。所以它是一个特殊的构造函数Error,而不是一个“子类”。

class Error1 extends Error
   constructor: (@message)->
     self = super
     self.name = 'Error1'
     return self

这是为了node: '0.10.1', 'coffee-script': '1.6.3'

文章中的最后一个例子bjb.io是(在 Coffeescript 中):

CustomError = (msg)->
  self = new Error msg
  self.name = 'CustomError'
  self.__proto__ = CustomError.prototype
  return self
CustomError.prototype.__proto__= Error.prototype
# CustomError::__proto__= Error::  # I think

这满足所有测试,util.isError, instanceof Error, instanceof CustomError, "#{new CustomError 'xxx'}"

于 2013-10-17T20:04:38.203 回答