At the beginning, I recommend an article, which describes the inheritance of js in a particularly comprehensive way. I just take the conclusions in it, and refer to
how Javascript implements inheritance in the future?
1. How to use inheritance
The commonly used in js is extends, and the usage is as follows:
class Father {
constructor(name) {
this.name = name
}
// 原型方法
// 即 Person.prototype.getName = function() { }
// 下面可以简写为 getName() {...}
getName = function () {
console.log('Person:', this.name)
}
}
class child extends Father {
constructor(name, age) {
super(name)
this.age = age
}
getAge = function () {
console.log('Age:', this.age)
}
}
const person = new child('Jim','28')
person.getName() // Person: Jim
person.getAge() // Age: 28
2. The method of implementing inheritance - parasitic combined inheritance
There are many ways to achieve inheritance. I will choose the best way to show it here, extends
and it is also a parasitic combination method.
function extend(father, child) {
// 用 Object.create 拷贝父亲的prototype
child.prototype = Object.create(father.prototype)
//手动挂上构造器,指向自己的构造函数
child.prototype.constructor = child
}
have a test
// 测试例子
function father() {
this.name = 'Tom';
this.play = [1, 2, 3];
}
father.prototype.getName = function () {
return this.name;
}
function child(friends) {
father.call(this)
this.friends = friends
}
// 继承
extend(father,child)
child.prototype.getFriends = function () {
return this.friends;
}
let person6 = new child('July');
console.log(person6.getName()); // Tom
console.log(person6.getFriends()); // July