简体   繁体   English

如何使用 Object.defineProperty 的导出指令?

[英]How to use export directive for Object.defineProperty?

It's clear how to use the export statement with object or function:很清楚如何将 export 语句与 object 或 function 一起使用:

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

But what if i'd like to extend prototype using Object.defineProperty但是,如果我想使用 Object.defineProperty 扩展原型怎么办

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

How to use export in this case?在这种情况下如何使用导出?

You don't really have to export anything, but in other files where you want to use the extended prototype, you have to import the file where you did it.您实际上不必导出任何内容,但是在您想要使用扩展原型的其他文件中,您必须导入您所做的文件。

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM