可能出现的性能问题
- 多次查找原型链:每次调用父类原型方法时,JavaScript 引擎都需要沿着原型链向上查找该方法,这在原型链较长时会消耗较多时间,影响性能。例如,多层继承时,查找深度增加,查找时间线性增长。
- 内存浪费:如果父类原型方法中有对父类实例的引用,而子类调用该方法时,可能会导致不必要的内存占用,因为父类实例可能包含大量数据,即便子类并不需要。
优化策略
- 方法绑定
- 原理:在子类构造函数中,使用
Function.prototype.bind
方法将父类原型方法绑定到子类实例上。这样,子类实例调用该方法时,直接调用绑定后的函数,无需再查找原型链。
- 代码示例:
function Parent() {
this.value = 10;
}
Parent.prototype.getVal = function() {
return this.value;
};
function Child() {
Parent.call(this);
this.getVal = this.getVal.bind(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
let child = new Child();
console.log(child.getVal());
- 使用
Object.assign
复制方法
- 原理:使用
Object.assign
方法将父类原型上的方法直接复制到子类原型上。这样子类调用这些方法时,直接从自身原型获取,避免了原型链查找。
- 代码示例:
function Parent() {
this.value = 20;
}
Parent.prototype.getVal = function() {
return this.value;
};
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Object.assign(Child.prototype, {
getVal: Parent.prototype.getVal
});
Child.prototype.constructor = Child;
let child = new Child();
console.log(child.getVal());