Inheriting from the Error object - where is the message property?

前端 未结 7 1236
面向向阳花
面向向阳花 2020-11-30 02:58

I noticed a strange behavior while defining custom error objects in Javascript:

function MyError(msg) {
    Error.call(this, msg);
    this.name = \"MyError\         


        
7条回答
  •  囚心锁ツ
    2020-11-30 03:37

    function MyError(msg) {
        var err = Error.call(this, msg);
        err.name = "MyError";
        return err;
    }
    

    Error doesn't manipulate this, it creates a new error object which is returned. That's why Error("foo") works aswell without the new keyword.

    Note this is implementation specific, v8 (chrome & node.js) behave like this.

    Also MyError.prototype.__proto__ = Error.prototype; is a bad practice. Use

    MyError.prototype = Object.create(Error.prototype, { 
      constructor: { value: MyError } 
    });
    

提交回复
热议问题