寻找黑客在原型被密封时填充对象

Looking for hacks to shim objects when their prototype are sealed

在我的上下文中,String 和String.prototype、Array 和Array.prototype、Object 和Object.prototype 是密封的。我无法控制这种密封。 我的上下文只支持 ES5,我想使用 ES6 垫片 (https://github.com/paulmillr/es6-shim) 来使用 ES6 优雅的方法,如 find()、reduce() 甚至 startsWith() ...

我无法使用这些 shim,因为当我尝试添加或编辑原型时会抛出错误。你知道绕过这个限制的一些技巧吗?我的意思是使用 Array.prototype.find() 而不提供我自己的实现。

例如,在能够使用 ES6 函数之前,我可以使用 new ES6Array([]) 的解决方案将是适合我的解决方案。我只是想避免自己实现 Shims。我想尽可能多地使用 paulmillr 实现。

是否可以使用阴影技巧来使用 paulmillr 实现? 我一直在尝试这样做,但它并没有导致任何合规的结果。

PS:这是 Salesforce Commerce Cloud 上下文

es6-shim 是一个 polyfill,如果原型被密封,肯定会失败,因为它应该修改它们。

这里需要的方法是 ponyfill。正如描述所说,

In general, you should not modify API's you don't own.

A ponyfill, in contrast, doesn't monkey patch anything, but instead exports the functionality as a normal module, so you can use it locally without affecting other code.

tl;dr; Polyfills are naughty as they patch native APIs, while ponyfills are pure and don't affect the environment.

其中一些在 NPM 上被标记为 ponyfill keyword

core-js 提供了 doesn't pollute global namespace 的库版本,因此可以用作 ponyfill,所以通常没有理由再看下去了:

import * as find from 'core-js/library/fn/array/find';

find(array, 'foo')

请注意,一些 core-js/library 导出是 polyfill 实现(PromiseMap 等):

import { Promise as PolyfilledPromise } from 'core-js/library';

PolyfilledPromise.resolve();

而其他的是 polyfilled 方法的集合,因为为它们提供独立的实现是不切实际或不可能的(ArrayObject):

import { Array as arrayPonyfills } from 'core-js/library';
const { find } = arrayPonyfills;

find.call(array, 'foo');