[英]Exporting Object.defineProperty
我有這段代碼:
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()。
我該如何解決?
謝謝你。
因為代碼只執行副作用,所以將它導入到不同模塊中的變量實際上沒有意義。 為它的副作用導入它就足以使用String.prototype.startsWith
。
// A.js
if (!String.prototype.startsWith) {
// etc
// B.js
import './A.js';
console.log('abc'.startsWith('a')); // true
如果您必須導出某些內容,並且不希望導入產生副作用,則可以導出一個 function,在調用時將其分配給原型。
// A.js
export const polyfillStartsWith = () => {
if (!String.prototype.startsWith) {
// etc
// B.js
import { polyfillStartsWith } from './A.js';
polyfillStartsWith();
console.log('abc'.startsWith('a')); // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.