寄生组合式继承(最理想的)
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue', 'yellow'];
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(name, age) {
// 核心代码①
Parent.call(this, name);
this.age = age;
}
// 核心代码②
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
ES6中class的继承
class Parent(name, age) {
this.name = name;
this.age= age;
this.colors = ['red', 'blue', 'yellow'];
toString() {
return this.color.join(',');
}
}
class Child extends Parent {
constructor(name, age, color) {
// 调用父类的constructor(name, age)
super(name, age);
this.color = color;
}
toString() {
return this.color + ': ' + super.toString(); // 调用父类的toString()
}
}
关键词:JavaScript继承
所属分类:网站技术
本文地址:https://me.i-i.me/article/56.html
评论