如何不使用Proxy将JavaScript标识符转换为字符串?
不使用Proxy获取标识符字符串的方案
当然存在无需Proxy的实现方式,以下是几种实用方案:
1. 利用对象计算属性名提取
通过构造包含目标标识符的对象,直接提取其属性名:
class C { doSomething() { console.log('hello'); } } // 核心逻辑:将目标标识符作为对象属性,再提取键名 const getPropStr = (obj) => Object.keys(obj)[0]; const str = getPropStr({ doSomething: undefined }); console.log(str); // 输出 "doSomething" const c = new C(); c[str](); // 执行目标方法
即使标识符被混淆(比如变成_abc123),只需替换对象中的属性名,就能自动得到对应的字符串,无需提前知晓混淆后的名称。
2. 通过箭头函数toString提取参数名
利用箭头函数的toString()会保留参数标识符的特性,配合正则提取:
class C { doSomething() { console.log('hello'); } } const getPropStr = (fn) => fn.toString().match(/^\(([^)]+)\)/)[1]; const str = getPropStr((doSomething) => {}); console.log(str); // 输出 "doSomething" const c = new C(); c[str]();
注意:该方法依赖JS引擎对函数toString()的实现,主流引擎均支持,但极端压缩场景下可能失效。
3. 遍历类原型获取方法名
若目标是类的原型方法,可直接遍历原型属性筛选:
class C { doSomething() { console.log('hello'); } } // 筛选出原型上的非构造函数方法 const str = Reflect.ownKeys(C.prototype).find(key => typeof C.prototype[key] === 'function' && key !== 'constructor' ); console.log(str); // 输出 "doSomething" const c = new C(); c[str]();
适合明确要找类的方法,但不知道具体名称的场景。
内容的提问来源于stack exchange,提问作者Andrew Parks
相关产品推荐
相关产品推荐

