如何从A.js导出startsWith供B.js以A.startsWith()形式调用?
解决方案
你的核心问题是混淆了扩展String原型和导出独立函数的逻辑,原来的写法既存在语法错误,也没把目标函数单独导出。可以按以下步骤修改:
1. 重构A.js代码
先把startsWith的实现逻辑抽成独立函数,再同时完成原型扩展和模块导出:
// A.js function startsWith(searchString, position) { position = position || 0; return this.lastIndexOf(searchString, position) === position; } // 仅当原生不支持时,扩展String原型 if (!String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { enumerable: false, configurable: false, writable: false, value: startsWith }); } // 导出这个独立函数 export { startsWith };
2. 在B.js中调用
现在你可以通过两种方式使用:
- 直接调用导出的函数(注意此时需要手动绑定
this,或者调整为纯函数逻辑):
// B.js import { startsWith } from './A.js'; // 方式1:绑定字符串作为this上下文 const str = 'Hello World'; console.log(startsWith.call(str, 'Hello')); // 输出 true // 方式2:修改A.js中的函数为纯函数(更推荐) // 若把A.js里的函数改成: // function startsWith(str, searchString, position = 0) { // return str.lastIndexOf(searchString, position) === position; // } // 即可直接调用: // console.log(startsWith('Hello World', 'Hello'));
- 同时也能使用原生风格的字符串调用(因为原型已被扩展):
const str = 'Hello World'; console.log(str.startsWith('Hello')); // 输出 true
原写法报错原因
exports Object.defineProperty(...)是语法错误,exports后需跟赋值语句,比如exports.startsWith = xxx。- 即便修正语法,
Object.defineProperty的返回值是被修改的对象(此处为String.prototype),而非你需要的startsWith函数,因此导出后无法通过A.startsWith()调用目标逻辑。
内容的提问来源于stack exchange,提问作者zhin dins
相关产品推荐
相关产品推荐

