MST

星途 面试题库

面试题:JavaScript 反射 API 与元编程

阐述 JavaScript 反射 API 与元编程的紧密联系。如何利用反射 API 实现一个元编程场景,例如创建一个通用的代理函数,能够根据传入的对象和方法名,动态调用对象方法并在调用前后执行特定逻辑,同时考虑处理异步方法的情况。
49.8万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

JavaScript 反射 API 与元编程的紧密联系

  1. 元编程概念:元编程是指程序能够将自身当作数据进行处理,或者创建、分析、修改其他程序的能力。在 JavaScript 中,这意味着代码可以在运行时检查和修改自身结构与行为。
  2. 反射 API 作用:JavaScript 的反射 API(Reflect对象)提供了一系列方法,这些方法与对象的底层操作相对应,比如属性的获取、设置、删除等。它为元编程提供了基础能力,使开发者可以以编程方式操作对象的元数据,像访问对象的属性描述符、调用对象的内部方法等,从而实现对对象行为的动态控制,这正是元编程的核心。

利用反射 API 实现通用代理函数

function createProxyFunction(target, methodName, preLogic, postLogic) {
    return async function (...args) {
        // 调用前执行特定逻辑
        if (typeof preLogic === 'function') {
            preLogic();
        }
        let result;
        const method = Reflect.get(target, methodName);
        if (typeof method === 'function') {
            if (typeof method.constructor === 'function' && method.constructor.name === 'AsyncFunction') {
                result = await method.apply(target, args);
            } else {
                result = method.apply(target, args);
            }
        }
        // 调用后执行特定逻辑
        if (typeof postLogic === 'function') {
            postLogic();
        }
        return result;
    };
}

使用示例

const myObject = {
    async asyncMethod() {
        return 'Async result';
    },
    syncMethod() {
        return 'Sync result';
    }
};

const asyncProxy = createProxyFunction(myObject, 'asyncMethod', () => console.log('Before async call'), () => console.log('After async call'));
const syncProxy = createProxyFunction(myObject,'syncMethod', () => console.log('Before sync call'), () => console.log('After sync call'));

asyncProxy().then(console.log);
console.log(syncProxy());

上述代码中,createProxyFunction函数接收目标对象、方法名以及调用前后的逻辑函数。通过Reflect.get获取目标对象的方法,然后判断方法是否为异步函数,分别进行调用,并在前后执行相应逻辑。