MST

星途 面试题库

面试题:JavaScript中为已有类添加方法时如何防止命名冲突

在JavaScript中,当我们需要为一个已有的类添加方法时,怎样做可以有效避免新添加的方法名与类中已有的属性或方法名产生命名冲突?请举例说明。
13.5万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 使用命名空间或前缀
    • 为新添加的方法名添加特定的前缀,这样可以降低与已有属性或方法名冲突的可能性。
    • 例如:
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();
  1. 使用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();
  1. 检查是否存在同名属性或方法后再添加
    • 在添加新方法之前,先检查类的原型上是否已经存在同名的属性或方法。
    • 例如:
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();