从内置类`Error`扩展(继承)

时间:2014-12-28 17:40:01

标签: javascript inheritance built-in

我尝试在JS中编写自己的HTTPError对象。我的代码如下所示

"use strict"; 

HTTPError.prototype = Object.create( Error.prototype );
HTTPError.prototype.constructor = HTTPError;

function HTTPError( msg, httpStatus, httpStatusText, fileName, lineNumber )  {
  var _httpStatus = httpStatus;
  var _httpStatusText = httpStatusText;

  // Public and privileged methods

  this.httpStatus = function() {
    return _httpStatus;
  }

  this.httpStatusText = function() {
    return _httpStatusText;
  }

  // C'tor starts here
  Error.call( this, msg, fileName, lineNumber );
  this.name = "HTTPError";
}

HTTPError.prototype.toString = function() {
  var name = this.name;
  name = (typeof name !== "string") ? 'HTTPError' : name;

  var msg = this.message;
  console.log( "This is msg: " + msg );
  msg = (typeof msg !== "string") ? '' : msg;

  var status = '(Status: ' + this.httpStatus() + ' - ' + this.httpStatusText() + ')';

  if (name === '') {
    return msg + ' ' + status;
  }
  if (msg === '') {
    return name + ' ' + status;
  }

  return name + ': ' + msg + ' ' + status;
}

方法toString的灵感来自MDN Error.toString referenceError - 构造函数的签名取自MDN Error reference

问题是toString()方法从不打印错误消息。代码行console.log( "This is msg: " + msg )仅用于调试目的。此行显示msg未定义,因此设置为''。但为什么它没有定义?由于某种原因,message属性似乎不存在,但我调用了父Error构造函数。我做错了什么?

0 个答案:

没有答案