【问题标题】:Exporting Object.defineProperty导出 Object.defineProperty
【发布时间】:2022-12-13 14:04:45
【问题描述】:

我有这段代码:

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });
}

我如何使用A.startsWith()startsWith从A.js导出到B.js?

我尝试使用 exports Object.defineProperty(String.prototype, 'startsWith', { 但出现错误

在文件 B.js 中,我使用的是 import * as A from './A.js',但我无法使用 A.startsWith()。

我该如何解决?

谢谢你。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    因为代码只执行副作用,所以将它导入到不同模块中的变量实际上没有意义。导入它的副作用将足以使用String.prototype.startsWith

    // A.js
    if (!String.prototype.startsWith) {
      // etc
    
    // B.js
    import './A.js';
    console.log('abc'.startsWith('a')); // true
    

    如果您必须导出某些东西,并且您不希望仅从导入中产生副作用,则可以导出一个函数,该函数在调用时分配给原型。

    // A.js
    export const polyfillStartsWith = () => {
      if (!String.prototype.startsWith) {
        // etc
    
    // B.js
    import { polyfillStartsWith } from './A.js';
    polyfillStartsWith();
    console.log('abc'.startsWith('a')); // true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 2011-04-19
      • 2023-03-24
      • 1970-01-01
      • 2023-01-07
      • 2021-10-18
      • 2017-08-07
      相关资源
      最近更新 更多