面試題3:ES五、ES6兩種方式實現繼承

寫一個類Person,擁有屬性age和name,擁有方法say(something)
再寫一個類Superman,繼承Person,擁有本身的屬性power,擁有本身的方法fly(height)this

// ES5
function Person (age, name) {
  this.age = age
  this.name = name
}
Person.prototype = {
  say: function() {
     console.log("hello");
  }
};

var Superman = function(name, age, power) {
  Person.call(this, name, age, power);
  this.power = power;
};

Superman.prototype = new Person();
Superman.prototype.fly = function(height) {
  console.log(height);
}

// ES6
class Person {
  constructor(age, name) {
    this.age = age;
    this.name = name;
  }
  say () {
    console.log("hello");
  }
}

class Superman extends Person {
  constructor (age, name, power) {
    super(age, name);
    this.power = power;
  }

  fly (height) {
    console.log(height);
  }
}
相關文章
相關標籤/搜索