js 实现重写
重写方法的基本实现
在JavaScript中,可以通过修改对象的属性或方法来重写已有功能。例如,重写一个对象的方法:
const obj = {
originalMethod: function() {
console.log('Original method');
}
};
// 重写方法
obj.originalMethod = function() {
console.log('Overridden method');
};
使用原型链重写
通过修改原型链上的方法可以实现对所有实例的重写:
function MyClass() {}
MyClass.prototype.method = function() {
console.log('Original method');
};
// 重写原型方法
MyClass.prototype.method = function() {
console.log('Overridden method');
};
重写内置对象方法
JavaScript允许重写内置对象的方法,但不推荐这种做法:
Array.prototype.push = function() {
console.log('Overridden push method');
};
使用Proxy实现高级重写
Proxy可以拦截并重定义对象的基本操作:
const target = {
message: 'Hello'
};
const handler = {
get: function(target, prop) {
return prop in target ? target[prop] : 'Default value';
}
};
const proxy = new Proxy(target, handler);
函数柯里化实现重写
通过柯里化可以改变函数的行为:
function original(a, b) {
return a + b;
}
function override(fn) {
return function(a, b) {
return fn(a, b) * 2;
};
}
const newFn = override(original);
使用装饰器模式
装饰器模式允许在不改变原对象的基础上动态添加功能:
function decorate(obj, prop, decorator) {
const original = obj[prop];
obj[prop] = function() {
return decorator(original.apply(this, arguments));
};
}
const calculator = {
add: (a, b) => a + b
};
decorate(calculator, 'add', result => result * 10);
重写类方法
在ES6类中重写方法:
class Parent {
method() {
console.log('Parent method');
}
}
class Child extends Parent {
method() {
super.method(); // 调用父类方法
console.log('Child method');
}
}
使用Object.defineProperty
通过属性描述符精确控制重写行为:

const obj = {};
Object.defineProperty(obj, 'prop', {
get: function() {
return 'Overridden getter';
},
set: function(value) {
console.log('Overridden setter:', value);
}
});
每种重写方法都有其适用场景,需要根据具体需求选择最合适的实现方式。






