盒子
盒子
文章目录
  1. 原则:
  2. a、构造函数引用属性不共享
  3. b、原型属性共享
  4. 1、原型链继承
  5. 2、构造函数
  6. 3、构造函数+原型链
  7. 4、计生组合

再次理解继承

原则:

a、构造函数引用属性不共享

b、原型属性共享

1、原型链继承

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name = 'xiaoming') {
this.name = name;
this.shose = ['nike', 'puma', 'vans'];
}
Person.prototype.run = function() {
console.log(`${this.name} is running...`);
}
function Student(age = 20) {
this.age = age;
}
Student.prototype = new Person();
var s = new Student();
var s1 = new Student();

优点:都继承了构造属性和原型属性
缺点:但是构造引用属性存在共享问题

2、构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person(name = 'xiaoming') {
this.name = name;
this.shose = ['nike', 'puma', 'vans'];
}
Person.prototype.run = function() {
console.log(`${this.name} is running...`);
}
function Student(age = 20) {
Person.call(this);
this.age = age;
}
var s = new Student();
var s1 = new Student();

优点:构造引用属性不存在共享问题
缺点:原型属性没有得到继承

3、构造函数+原型链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Person(name = 'xiaoming') {
this.name = name;
this.shose = ['nike', 'puma', 'vans'];
}
Person.prototype.run = function() {
console.log(`${this.name} is running...`);
}
function Student(age = 20) {
Person.call(this);
this.age = age;
}
Student.prototype = new Person();
var s = new Student();
var s1 = new Student();

优点:构造引用属性不共享,原型方法也能继承
缺点:构造属性重复,子类实例和原型都存在构造属性,占空间

4、计生组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Person(name = 'xiaoming') {
this.name = name;
this.shose = ['nike', 'puma', 'vans'];
}
Person.prototype.run = function() {
console.log(`${this.name} is running...`);
}
function Student(age = 20) {
Person.call(this);
this.age = age;
}
function create(o) {
function F(){};
F.prototype = o;
return new F();
}
Student.prototype = create(Person.prototype);
var s = new Student();
var s1 = new Student();

优点:构造引用属性不共享,原型方法也能继承,构造属性不重复
缺点:无
备注:上面的create()方法其实就是Object.create()方法的实现,最后,请按照代码顺序画出内存空间的变化!

支持一下
扫一扫,支持 Alin
  • 微信扫一扫
  • 支付宝扫一扫