【问题标题】:How to use export directive for Object.defineProperty?如何为 Object.defineProperty 使用导出指令?
【发布时间】:2020-07-14 22:47:20
【问题描述】:

很清楚如何将导出语句与对象或函数一起使用:

export function take(source, n) {
         return source.slice(0, n);         
}

但是如果我想使用 Object.defineProperty 扩展原型怎么办

Object.defineProperty(Enumerable.prototype, 'take', {
  value(n) {
    return [].concat(this).slice(0, n);
  },
});

这种情况下如何使用导出?

【问题讨论】:

  • Enumerable 构造函数的实例将在其原型链中具有该属性。

标签: javascript ecmascript-2016


【解决方案1】:

您实际上不必导出任何内容,但是在您想要使用扩展原型的其他文件中,您必须导入您所做的文件。

// enumerable.js
Object.defineProperty(Enumerable.prototype, 'take', {
  value(n) {
    return [].concat(this).slice(0, n);
  },
});
// index.js
import * as enumerable from './enumerable.js'

console.log(Enumerable.prototype.take) // will be a function here

【讨论】:

  • 没有从enumerable.js 导出的任何东西要导入。我认为导入是多余的?
  • 如果不导入,JS引擎不会加载enumerable.js文件,因此它不知道Enumerable的原型有什么变化。这就是为什么不建议修改原型而我们应该扩展类的原因。
  • 如果你加载一个文件只是为了副作用,你不需要命名它,例如import './enumerable.js';
猜你喜欢
  • 2022-12-13
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2014-07-30
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
相关资源
最近更新 更多