【问题标题】:Conditions in class constructor javascript类构造函数javascript中的条件
【发布时间】:2017-09-11 13:58:33
【问题描述】:

我有这个代码

class Person{
  constructor(person){
    this._name=person._name;
    this._age=person._age;
  }
}

class Employee extends Person{
  constructor(person){
    if(person instanceof Person){
    super(person);
    }else{
       throw 'passed object is not a valid person object';
    }
  }
}

let emp=new Employee({_name:'Uday',_age:24});
console.log(emp);

只有当我得到有效的 person 对象时,我才想调用 super(person)。我在babeljs.io 中收到此错误this hasn't been initialised - super() hasn't been called。如何确保我只将有效的person 对象传递给超类?

【问题讨论】:

  • 为什么应该是person的实例?在您对new Employee 的调用中,您不是传递一个人对象,而是一个看起来像一个的普通对象。另外,如果person 不是您想要的那样,您希望发生什么? new总是返回一个构造对象,除非你当然抛出错误。
  • 如果传入Employee构造函数的对象不是有效的Person对象,我想抛出异常。
  • 所以你希望底部的示例代码抛出异常,对吧?
  • 我认为如果传递给它的参数为空,您可以稍微修改您的超类以引发异常。然后,在派生类中,检查人员是否有效。如果不是你通过 super(null)
  • 你不能,super 方法必须在构造函数的第一个位置调用。你在这里有不连贯性,你不能从Personextends而不打电话给super(person),这是没有意义的。所以你必须在之后检查这个,或者在 Person 类中

标签: javascript node.js ecmascript-6 es6-class


【解决方案1】:

不知道它是否在打字稿中,但这可能会解决您的问题。

class Person{
  constructor(person){
  this._name=person._name;
  this._age=person._age;
  }
}

 class Employee extends Person{
    constructor(person){
    let temp = null;
    if(!(person instanceof Person))
     throw new Error("message");
     super(temp);
  }
}

let emp=new Employee({_name:'Uday',_age:24});
console.log(emp);

【讨论】:

    【解决方案2】:

    下面的代码适合我。我认为主要问题是您在 if 语句中调用 super。如果person 不是Person 类的实例,它将永远不会被调用,因此 babel 会抱怨。

    class Person{
      constructor(person){
        this._name=person._name;
        this._age=person._age;
      }
    }
    
    class NotPerson {
      constructor(person){
        this._name=person._name;
        this._age=person._age;
      }
    }
    
    class Employee extends Person{
      constructor(person){
        if(!(person instanceof Person)){
          throw new Error('Not a person!');
        }
        super(person);
      }
    }
    
    let per= new Person({_name: 'Bah', _age: 20});
    let per2 = new NotPerson({_name: 'Bah', _age: 20});
    let emp=new Employee(per);
    // let emp2= new Employee(per2); this will throw an error!
    
    console.log(emp);
    //console.log(emp2);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2022-12-09
      • 1970-01-01
      相关资源
      最近更新 更多