JavaScript 类与继承

原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// 本质 => Child.prototype.__proto__ = Parent.prototype
function inherit(Child, Parent) {
function F(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child; //修复constructor
}

function Animal(legsNumber){
this.legsNumber = legsNumber;
}

function Dog(){
this.name = name;
Animal.call(this, 4); // **关键代码**
}

inherit(Dog, Animal); // **关键代码**

Dog.prototype.kind = '狗'
Dog.prototype.say = function(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}

const d1 = new Dog('啸天') // Dog 函数就是一个类
console.dir(d1)

类继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Animal{
constructor(legsNumber){
this.legsNumber = legsNumber;
}
run(){}
}

class Dog extends Animal{
constructor(name){
super(4);
this.name = name;
}
say(){
console.log(`汪汪汪~ 我是${this.name},我有${this.legsNumber}条腿。`)
}
}


JavaScript 类与继承
http://example.com/2023/01/08/JavaScript基础 - 类与继承/
作者
Ray
发布于
2023年1月8日
许可协议