js override 实现
方法一:原型链继承与重写
通过原型链继承父类方法,并在子类中重新定义同名方法实现覆盖(override)。父类方法可通过 ParentClass.prototype.methodName.call(this) 调用。
function ParentClass() {}
ParentClass.prototype.greet = function() {
return "Hello from Parent";
};
function ChildClass() {}
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.greet = function() {
return "Hi from Child";
};
const child = new ChildClass();
console.log(child.greet()); // 输出: "Hi from Child"
方法二:ES6 Class 语法
使用 extends 和 super 实现方法覆盖。super 关键字可调用父类方法。
class Parent {
greet() {
return "Parent says hello";
}
}
class Child extends Parent {
greet() {
return "Child says hi";
}
}
const instance = new Child();
console.log(instance.greet()); // 输出: "Child says hi"
方法三:对象属性直接覆盖
直接修改对象的属性或方法,适用于实例级别的覆盖。
const obj = {
greet: function() {
return "Original";
}
};
obj.greet = function() {
return "Overridden";
};
console.log(obj.greet()); // 输出: "Overridden"
方法四:使用 Object.assign 合并对象
通过合并对象实现方法替换,保留未覆盖的原有方法。
const base = {
methodA() { return "A"; },
methodB() { return "B"; }
};
const override = {
methodA() { return "New A"; }
};
const result = Object.assign({}, base, override);
console.log(result.methodA()); // 输出: "New A"
console.log(result.methodB()); // 输出: "B"
方法五:高阶函数包装
通过函数包装动态修改方法行为,保留原方法的引用。

function original() {
return "Original";
}
function override(fn) {
return function() {
return "Modified: " + fn();
};
}
const wrapped = override(original);
console.log(wrapped()); // 输出: "Modified: Original"
注意事项
- 原型链覆盖会影响所有实例,而对象属性覆盖仅影响当前实例。
- 使用
super时需确保在class和extends上下文中。 - 直接修改内置对象原型(如
Array.prototype)可能导致不可预期行为,应谨慎使用。






