ES5、ES6两种方式实现继承
文章目录
写一个类Person,拥有属性age和name,拥有方法say(something)
再写一个类Superman,继承Person,拥有自己的属性power,拥有自己的方法fly(height)
// ES5
function Person (age, name) {
this.age = age
this.name = name
}
Person.prototype = {
say: function() {
console.log("hello");
}
};
var Superman = function(age, name, power) {
Person.call(this, age, name);
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);
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论