JavaScript深入之继承的多种方式和优缺点
对象得原型
JS
当中每个对象都有一个特殊的内置属性[[prototype]]
,这个特殊的对象可以指向另外一个对象- 当我们通过引用对象的属性
key
来获取一个value
时,它会触发[[Get]]
的操作 - 这个操作会首先检查该属性是否有对应的属性,如果有的话就使用它
- 如果对象中没有改属性,那么会访问对象的
[[prototype]]
内置属性指向的对象上的属性
- 当我们通过引用对象的属性
- 那么如果通过字面量直接创建一个对象,这个对象也会有这样的属性吗?如果有,应该如何获取这个属性呢?
- 答案是有的,只要是对象都会有这样的一个内置属性;
- 获取的方式有俩种
- 通过对象的
__proto__
属性可以获取到 (属于早期浏览器实现,存在兼容性问题) Object.getPrototypeOf()
- 通过对象的
函数的原型
prototype
// 箭头函数 没有 prototype属性、没有单独的 this (它只会从自己的作用域链的上一层继承this)
// 不绑定arguments、不能用作构造器 、箭头函数不能用作函数生成器。
var Foo = () => {};
console.log(Foo.prototype); // undefined
constructor
属性
- 事实上原型对象上面是有一个属性的:
constructor
- 默认情况下原型上都会添加一个属性叫做
constructor
,这个constructor
指向当前的函数对象
- 默认情况下原型上都会添加一个属性叫做
function Person() {}
console.log(Object.getOwnPropertyDescriptors(Person.prototype))
/*
{
constructor: {
value: [Function: Person],
writable: true,
enumerable: false,
configurable: true
}
}
*/
原型链继承
function Parent () {
this.name = 'kevin';
this.friend = ['kevin', 'daisy'];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child () {}
// 下面这俩步不能调换顺序
Child.prototype = new Parent();
Child.prototype.study = function () {
console.log('开始学习...');
}
var child1 = new Child();
var child2 = new Child();
child1.friend.push('小明');
console.log(child1.getName()) // kevin
console.log(child1.friend); // ["kevin", "daisy", "小明"]
console.log(child2.friend); // ["kevin", "daisy", "小明"]
// 引用类型的属性被所有实例共享
// 但是这样并没有影响是因为 相当于再 Child 实例上面添加了 friend 属性,所以并不会再根据原型链再往上一级查找
child1.friend = ['xiaoming']
child2.friend = ['xiaohong']
console.log(child1.friend); // ["xiaoming"]
console.log(child2.friend); // ["xiaohong"]
// 对象原型上面还是有 friend 属性的
console.log(child1.__proto__.friend); // [ 'kevin', 'daisy', '小明' ]
缺点:
- 引用类型的属性被所有实例共享
- 在创建
Child
的实例时,不能向Parent
传参 - 打印
child
对象,继承的属性是看不到
借用构造函数 (经典继承) 借助 call
function Parent (name,age) {
this.name = name;
this.age = age;
this.friend = ['kevin', 'daisy'];
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child (name,age) {
Parent.call(this,name,age)
}
var child1 = new Child();
var child2 = new Child();
child1.friend.push('小明');
console.log(child1.friend); // [ 'kevin', 'daisy', '小明' ]
console.log(child2.friend); // [ 'kevin', 'daisy' ]
优点:
- 避免了引用类型的属性被所有实例共享
- 可以在
Child
中向Parent
传参
缺点:
-
方法都在构造函数中定义,每次创建实例都会创建一遍方法。
Parent.call()
-
child1
的原型对象上会多出一些属性, 但是这些属性是没有存在的必要-
console.log(child1.friend); // [ 'kevin', 'daisy' ] 是属于 Parent 上面的属性
-
-
只能继承父类的实例属性和方法,不能继承原型属性或者方法
-
child1.getName() // 会报错 Child.prototype = new Parent(); // 解决无法父类继承原型属性或者方法,但是 Child.prototype.constructor 是 Parent
-
组合继承
function Parent (name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
// 第二次调用 Parent()
Parent.call(this, name);
this.age = age;
}
// 第一次调用 Parent()
Child.prototype = new Parent();
// Child constructor 正确指向
Child.prototype.constructor = Child;
var child1 = new Child('kevin', '18');
child1.colors.push('black');
console.log(child1.name); // kevin
console.log(child1.age); // 18
console.log(child1.colors); // ["red", "blue", "green", "black"]
var child2 = new Child('daisy', '20');
console.log(child2.name); // daisy
console.log(child2.age); // 20
console.log(child2.colors); // ["red", "blue", "green"]
优点:
- 融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
缺点:
- 通过注释发现
Parent
俩次调用,多构造一次就多进行了一次性能开销,这是我们不愿看到的
那么是否有更好的办法解决这个问题呢? 寄生组合式继承 可以更好地解决这里的问题。
上面介绍的更多是围绕着构造函数的方式,那么对于 JavaScript
的普通对象,怎么实现继承呢?
原型式继承
function createObj(obj){
function F(){}
F.prototype = obj
return new F()
}
var person = {
name: 'kevin',
friends: ['daisy', 'kelly']
}
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = 'person1';
console.log(person2.name); // kevin
person1.friends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]
缺点:
包含引用类型得属性值始终都会共享相应的值,这点和原型链继承一样
注意:
修改 person1.name
的值,person2.name
的值并未发生改变,并不是因为person1
和person2
有独立的 name
值,而是因为person1.name = 'person1'
,给person1
添加了 name
值,并非修改了原型上的 name
值。
寄生式继承
创建一个仅用于封装继承过程的函数,该函数在内部以某种形式来做增强对象,最后返回对象。
function Parent (name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
Parent.call(this, name);
this.age = age;
}
// 关键的三步
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child('kevin', '18');
console.log(child1);
引用《JavaScript高级程序设计》中对寄生组合式继承的夸赞就是:
这种方式的高效率体现它只调用了一次 Parent
构造函数,并且因此避免了在 Parent.prototype
上面创建不必要的、多余的属性。与此同时,原型链还能保持不变;因此,还能够正常使用 instanceof
和 isPrototypeOf
。开发人员普遍认为寄生组合式继承是引用类型最理想的继承范式。
寄生组合式继承封装
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
// 当我们使用的时候:
prototype(Child, Parent);
ES5 / ES6
的继承除了写法以外还有什么区别?
class
- 严格模式
- 不存在提升
class
的所有方法(包括静态方法和实例方法)都是不可枚举的。class
的所有方法(包括静态方法和实例方法)都没有原型对象 prototype,所以也没有[[construct]]
,不能使用new
来调用。- 必须使用
new
调用class
。 class
内部无法重写类名。
class
可以通过 extends
关键字实现继承,继承 父类 的所有属性和方法
子类必须在**constructor
方法中调用super
方法**,否则新建实例时会报错。这是因为子类自己的this
对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用**super
方法**,子类就得不到this
对象**。
ES5
的继承,实质是先创造子类的实例对象this
,然后再将父类的方法添加到this
上面(Parent.apply(this)
)。
function Super() {}
function Sub() {}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub;
var sub = new Sub();
Sub.__proto__ === Function.prototype;
而通过 ES5
的方式,Sub.__proto__ === Function.prototype
ES6
的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this
上面(所以必须先调用super
方法),然后再用子类的构造函数修改this
。
class Super {}
class Sub extends Super {}
const sub = new Sub();
Sub.__proto__ === Super;
子类可以直接通过__proto__
寻址到父类。