class 构造函数中的条件 javascript

Conditions in class constructor javascript

我有这个代码

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 对象传递给超级 class?

不知道是不是打字稿,但这可能会解决你的问题。

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);

下面的代码适合我。我认为主要问题是您在 if 语句中调用 super 。如果 person 不是 Person class 的实例,它将永远不会被调用,因此 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);