- 使用命名空间或前缀
- 为新添加的方法名添加特定的前缀,这样可以降低与已有属性或方法名冲突的可能性。
- 例如:
class MyClass {
constructor() {
this.data = 'initial data';
}
}
// 为MyClass添加新方法,使用前缀 'new_'
MyClass.prototype.new_doSomething = function() {
console.log('Doing something new:', this.data);
};
const instance = new MyClass();
instance.new_doSomething();
- 使用WeakMap进行私有方法模拟(间接避免冲突)
- WeakMap 可以用来存储对象的私有数据和方法。因为 WeakMap 的键是对象,所以可以避免与对象自身的属性和方法名冲突。
- 例如:
const privateMethods = new WeakMap();
class AnotherClass {
constructor() {
// 为每个实例创建私有方法
privateMethods.set(this, function() {
console.log('This is a private method');
});
}
publicCallPrivate() {
const privateMethod = privateMethods.get(this);
if (privateMethod) {
privateMethod();
}
}
}
const anotherInstance = new AnotherClass();
anotherInstance.publicCallPrivate();
- 检查是否存在同名属性或方法后再添加
- 在添加新方法之前,先检查类的原型上是否已经存在同名的属性或方法。
- 例如:
class CheckedClass {
constructor() {
this.value = 10;
}
}
function addNewMethodIfNotExists(targetClass, methodName, methodFunction) {
if (!targetClass.prototype.hasOwnProperty(methodName)) {
targetClass.prototype[methodName] = methodFunction;
}
}
addNewMethodIfNotExists(CheckedClass, 'newFunction', function() {
console.log('New function added:', this.value);
});
const checkedInstance = new CheckedClass();
checkedInstance.newFunction();