本章将详细介绍 core-js
# 11.1 core-js 简介
core-js 是 JavaScript 标准库 API 的补丁集,现在,它已支持 ECMAScript 的部分提案 API、标准 API,同时也支持部分 WEB 标准。
比如,对于 Array.isArray() 方法,core-js 提供了补丁:
var toString = {}.toString;
function classof(it) {
return toString.call(it).slice(8, -1);
};
Array.isArray = Array.isArray || function isArray(arg) {
return classof(arg) == 'Array';
};
2
3
4
5
6
7
8
9
core-js 最初是作者为了满足自身项目需要开启的项目,提供一些补丁和工具函数,随后发布在社区,并越来越向标准化靠近,到现在,core-js 可以被认为是一个纯粹的标准库补丁集。
core-js 通常应用内置在 Babel 插件体系里,开发者以前较少用到,但它已经是前端开发的一个基础设施了。
# 11.2 core-js@2 与 core-js@3
截至 2021 年 2 月,core-js 广泛应用的有两个版本: core-js@2 和 core-js@3,其中 core-js@2 已经停止更新,建议使用 core-js@3 版本。
本身编写时,能看到 core-js@4 的一些注释了,也许本书出版的时候 core-js@4 已经发布
下表是 core-js@2 与 core-js@3 的部分区别:
core-js@2 | core-js@3 | |
|---|---|---|
| 是否更新 | 不再更新 | 更新中 |
| 性能 | 包体积较大(~2M) | 包进行了拆分: core-js/core-js-pure/core-js-compat |
| 特性支持 | 在 @2 的基础上,删除一些过时特性 在 @2 的基础上,新增对 web 标准的支持 |
在此,我们主要了解 core-js@3 版本的使用和原理,下文中如不特殊标注版本,均被认为是 core-js@3。其与 core-js@2 的差异,书中也会介绍。
core-js@3 的特点:
core-js支持最新的 ECMAScript 标准core-js支持 ECMAScript 标准库提案core-js支持一些 WHATWG/W3C 标准core-js最大限度提供模块化定义,使之可按需使用core-js支持污染和不污染全局变量的能力core-js和 Babel 紧密集成,便于项目使用
# 11.3 core-js@3 子模块分类
core-js@3 是 monorepo 项目,基于 lerna 进行模块管理,其核心 package 包括:
core-js/packages/core-js/core-js/packages/core-js-builder/core-js/packages/core-js-bundle/core-js/packages/core-js-compat/core-js/packages/core-js-pure/
接下来将介绍上述模块。
core-js/packages/core-js/定义全局的补丁(~500KB,压缩并且 gzipped 处理后 40KB)。
core-js 支持 ECMAScript 标准、ECMAScript 提案、一些 WEB 标准(WHATWG/W3C),也支持模块化。这些特点的实现,主要在
core-js/packages/core-js/目录里。源码中有以下约定:- ECMAScript 标准中的 API,以
es.xx.js命名,如es.array.every.js - ECMAScript 提案中的 API,以
esnext.xx.js命名,如esnext.map.of.js - WEB 标准中的 API,以
web.xx.js命名,如web.url-search-params.js
下表是
core-js/packages/core-js各子模块的功能以及对各个标准的支持情况:目录/文件 描述 支持ES标准 支持ES提案 支持WEB标准 packages/core-js/index.js 全部补丁,包括 ECMAScript 标准、ECMAScript 提案、WEB 标准 √ √ √ packages/core-js/es/ 进入 ECMAScript 标准的 API √ √ × packages/core-js/features/ 包含 es/、web/、proposals/目录下的所有 API√ √ √ ? packages/core-js/stable/ 稳定的 API,包括 ECMAScript 标准、WEB 标准 √ × √ packages/core-js/web/ WEB 标准 API × × √ packages/core-js/proposals/ index.js指向stage/目录,间接指向stage-0/目录。目录内其他文件均为试验阶段的 ES API× √ × packages/core-js/stage/ index.js指向stage-0/目录,目录内其他文件分别指向stage0~4√ √ × packages/core-js/internals/ 内部使用的工具函数,含 API 具体实现,不用于对外服务 √ √ √ packages/core-js/modules/ 提供 API 最终定义;文件命名与当前支持的阶段和标准相关。 √ √ √ - ECMAScript 标准中的 API,以
core-js/packages/core-js-pure提供了不污染全局变量的补丁,即模块化的使用。和 core-js@2 中的
core-js/library相当(~440KB)。举例:
// 局部变量 import from from 'core-js-pure/stable/array/from'; import flat from 'core-js-pure/stable/array/flat'; import Set from 'core-js-pure/stable/set'; import Promise from 'core-js-pure/stable/promise'; from(new Set([1, 2, 3, 2, 1])); flat([1, [2, 3], [4, [5]]], 2); Promise.resolve(32).then(x => console.log(x));1
2
3
4
5
6
7
8
9core-js/packages/core-js-bundlecore-js-bundle是一个完整的core-js打包后的版本,提供全局补丁定义。可以在浏览器环境使用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://unpkg.com/core-js-bundle@3.16.2/minified.js"></script> </head> <body> <script> console.log(globalThis.Array === Array); // true </script> </body> </html>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15也可以在 Node 环境使用:
require('core-js-bundle'); console.log(globalThis.Array === Array); // true1
2core-js/packages/core-js-compatcore-js-compat提供了目标环境对应的core-js需要提供的功能模块。
# 11.4 core-js 中的补丁
这里介绍一下 core-js 中某些 API 的补丁。
# 准备工作
core-js 内部提供了一个通用的工具方法(这里命名为 $),该方法定义在文件 core-js/packages/core-js/internals/export.js,类型定义如下。
module.exports = (options: object; source: object): void
该方法提供了一种快捷方式,将补丁实现快速应用在目标对象上。
比如,core-js/packages/core-js/modules/es.object.is.js 定义了 Object.is 方法的补丁,通用方法 $ 是这样为 Object 对象添加 is() 方法的:
var $ = require('../internals/export'); // 通用的工具方法 $
var is = require('../internals/same-value');
// `Object.is` method
// https://tc39.es/ecma262/#sec-object.is
$({ target: 'Object', stat: true }, {
is: is
});
2
3
4
5
6
7
8
$ 方法中,options 对象是配置项,在该例中指的是 { target: 'Object', stat: true }。source 对象描述了补丁的具体实现,在该例中指的是 { is: is }。
上述配置的目的是将 is() 方法添加到 Object 对象作为其静态方法: Object.is()。
以下是 options 各配置项的含义:
target: string | undefined描述
source中的属性名要添加到的目标对象。global: booleansource中的属性名要添加到的目标对象是否是全局对象。以
es.parse-float.js为例:var $ = require('../internals/export'); var parseFloatImplementation = require('../internals/number-parse-float'); // `parseFloat` method // https://tc39.es/ecma262/#sec-parsefloat-string $({ global: true, forced: parseFloat != parseFloatImplementation }, { parseFloat: parseFloatImplementation });1
2
3
4
5
6
7
8其配置的
global: true意味着,parseFloat会被添加到全局对象上。以
es.object.keys.js为例:// `Object.keys` method // https://tc39.es/ecma262/#sec-object.keys $({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { keys: function keys(it) { return nativeKeys(toObject(it)); } });1
2
3
4
5
6
7其没有配置
global: true,且配置的stat: true,意味着,keys()方法被设置在了Object对象上,构成了Object.keys()方法。stat: booleansource对象中的属性名是否是target的静态属性/方法。proto: boolean是否添加到
target描述的对象的prototype上。例如,
es.array.copy-within.js的内容是:// `Array.prototype.copyWithin` method // https://tc39.es/ecma262/#sec-array.prototype.copywithin $({ target: 'Array', proto: true }, { copyWithin: copyWithin });1
2
3
4
5copyWithin方法被设置到了Array.prototype.copyWithin。realforced: boolean是否强制覆盖原生实现。
bindwrapunsafeshamenumerable: booleannoTargetGet: boolean
# ECMAScript 标准的补丁
ECMAScript 标准涉及的特性比较多,笔者根据标准描述及 core-js 的文档/源码,整理了 ECMAScript 标准特性及其在 core-js 的实现路径。
# ECMAScript: Object
特性列表
分类 特性 路径 es.objectcore-js(-pure)/es|stable|features/objectes.object.assigncore-js(-pure)/es|stable|features/object/assignes.object.iscore-js(-pure)/es|stable|features/object/ises.object.set-prototype-ofcore-js(-pure)/es|stable|features/object/set-prototype-ofes.object.get-prototype-ofcore-js(-pure)/es|stable|features/object/get-prototype-ofes.object.get-own-property-descriptorcore-js(-pure)/es|stable|features/object/get-own-property-descriptores.object.get-own-property-descriptorscore-js(-pure)/es|stable|features/object/get-own-property-descriptorses.object.keyscore-js(-pure)/es|stable|features/object/keyses.object.valuescore-js(-pure)/es|stable|features/object/valueses.object.entriescore-js(-pure)/es|stable|features/object/entrieses.object.get-own-property-namescore-js(-pure)/es|stable|features/object/get-own-property-nameses.object.freezecore-js(-pure)/es|stable|features/object/freezees.object.from-entriescore-js(-pure)/es|stable|features/object/from-entrieses.object.sealcore-js(-pure)/es|stable|features/object/seales.object.prevent-extensionscore-js(-pure)/es|stable|features/object/prevent-extensionses.object.is-frozencore-js(-pure)/es|stable|features/object/is-frozenes.object.is-sealedcore-js(-pure)/es|stable|features/object/is-sealedes.object.is-extensiblecore-js(-pure)/es|stable|features/object/is-extensiblees.object.to-stringcore-js/es|stable|features/object/to-stringes.object.createcore-js(-pure)/es|stable|features/object/createes.object.define-propertycore-js(-pure)/es|stable|features/object/define-propertyes.object.define-propertiescore-js(-pure)/es|stable|features/object/define-propertieses.object.define-gettercore-js(-pure)/es|stable|features/object/define-getteres.object.define-settercore-js(-pure)/es|stable|features/object/define-setteres.object.lookup-gettercore-js(-pure)/es|stable|features/object/lookup-getteres.object.lookup-settercore-js(-pure)/es|stable|features/object/lookup-setter重点实现
TODO
# ECMAScript: Function
特性列表
分类 特性 路径 es.functioncore-js/es|stable|features/functiones.function.namecore-js/es|stable|features/function/namees.function.has-instancecore-js/es|stable|features/function/has-instancees.function.bindcore-js/es|stable|features/function/bindcore-js/es|stable|features/function/virtual/bind重点实现
TODO
# ECMAScript: Array
特性列表
分类 特性 路径 es.arraycore-js(-pure)/es|stable|features/arrayes.array.fromcore-js(-pure)/es|stable|features/array/fromes.array.is-arraycore-js(-pure)/es|stable|features/array/is-arrayes.array.ofcore-js(-pure)/es|stable|features/array/ofes.array.copy-withincore-js(-pure)/es|stable|features/array/copy-withines.array.fillcore-js(-pure)/es|stable|features/array/filles.array.findcore-js(-pure)/es|stable|features/array/findes.array.find-indexcore-js(-pure)/es|stable|features/array/find-indexes.array.iteratorcore-js(-pure)/es|stable|features/array/iteratores.array.includescore-js(-pure)/es|stable|features/array/includeses.array.slicecore-js(-pure)/es|stable|features/array/slicees.array.joincore-js(-pure)/es|stable|features/array/joines.array.index-ofcore-js(-pure)/es|stable|features/array/index-ofes.array.last-index-ofcore-js(-pure)/es|stable|features/array/last-index-ofes.array.everycore-js(-pure)/es|stable|features/array/virtual/everyes.array.somecore-js(-pure)/es|stable|features/array/virtual/somees.array.for-eachcore-js(-pure)/es|stable|features/array/for-eaches.array.mapcore-js(-pure)/es|stable|features/array/mapes.array.filtercore-js(-pure)/es|stable|features/array/filteres.array.reducecore-js(-pure)/es|stable|features/array/reducees.array.reduce-rightcore-js(-pure)/es|stable|features/array/reduce-rightes.array.reversecore-js(-pure)/es|stable|features/array/reversees.array.sortcore-js(-pure)/es|stable|features/array/sortes.array.flatcore-js(-pure)/es|stable|features/array/flates.array.flat-mapcore-js(-pure)/es|stable|features/array/flat-mapes.array.unscopables.flat?? es.array.unscopables.flat-map?? es.array.atcore-js(-pure)/es|stable|features/array/at重点实现
TODO
# ECMASCript: String and RegExp
特性列表
分类 特性 路径 es.stringcore-js(-pure)/es|stable|features/stringes.string.from-code-pointcore-js(-pure)/es|stable|features/string/from-code-pointes.string.rawcore-js(-pure)/es|stable|features/string/rawes.string.iteratorcore-js(-pure)/es|stable|features/string(/virtual)/iteratores.string.splitcore-js/es|stable|features/string/splites.string.code-point-atcore-js(-pure)/es|stable|features/string(/virtual)/code-point-ates.string.ends-withcore-js(-pure)/es|stable|features/string(/virtual)/ends-withes.string.includescore-js(-pure)/es|stable|features/string(/virtual)/includeses.string.repeatcore-js(-pure)/es|stable|features/string(/virtual)/repeates.string.pad-startcore-js(-pure)/es|stable|features/string(/virtual)/pad-startes.string.pad-endcore-js(-pure)/es|stable|features/string(/virtual)/pad-endes.string.starts-withcore-js(-pure)/es|stable|features/string(/virtual)/starts-withes.string.trimcore-js(-pure)/es|stable|features/string(/virtual)/trimes.string.trim-startcore-js(-pure)/es|stable|features/string(/virtual)/trim-startes.string.trim-endcore-js(-pure)/es|stable|features/string(/virtual)/trim-endes.string.match-allcore-js(-pure)/es|stable|features/string(/virtual)/match-alles.string.replace-allcore-js(-pure)/es|stable|features/string(/virtual)/replace-alles.string.at-alternative?? es.string.matchcore-js/es|stable|features/string/matches.string.replacecore-js/es|stable|features/string/replacees.string.searchcore-js/es|stable|features/string/searches.string.splitcore-js/es|stable|features/string/splites.string.anchorcore-js(-pure)/es|stable|features/string(/virtual)/anchores.string.bigcore-js(-pure)/es|stable|features/string(/virtual)/biges.string.blinkcore-js(-pure)/es|stable|features/string(/virtual)/blinkes.string.boldcore-js(-pure)/es|stable|features/string(/virtual)/boldes.string.fixedcore-js(-pure)/es|stable|features/string(/virtual)/fixedes.string.fontcolorcore-js(-pure)/es|stable|features/string(/virtual)/fontcolores.string.fontsizecore-js(-pure)/es|stable|features/string(/virtual)/fontsizees.string.italicscore-js(-pure)/es|stable|features/string(/virtual)(/virtual)/italicses.string.linkcore-js(-pure)/es|stable|features/string(/virtual)/linkes.string.smallcore-js(-pure)/es|stable|features/string(/virtual)/smalles.string.strikecore-js(-pure)/es|stable|features/string(/virtual)/strikees.string.subcore-js(-pure)/es|stable|features/string(/virtual)/subes.string.supcore-js(-pure)/es|stable|features/string(/virtual)/supes.string.substrcore-js(-pure)/es|stable|features/string(/virtual)/substres.escapecore-js/es|stable|features/escapees.unescapecore-js/es|stable|features/unescapees.regexpcore-js/es|stable|features/regexpes.regexp.constructorcore-js/es|stable|features/regexp/constructores.regexp.dot-allcore-js/es|stable|features/regexp/dot-alles.regexp.flagscore-js(-pure)/es|stable|features/regexp/flagses.regexp.stickycore-js/es|stable|features/regexp/stickyes.regexp.testcore-js/es|stable|features/regexp/test重点实现
TODO
# ECMAScript: Number
特性列表
分类 特性 路径 es.numbercore-js(-pure)/es|stable|features/numberes.number.constructorcore-js/es|stable|features/number/constructores.number.epsiloncore-js(-pure)/es|stable|features/number/epsilones.number.is-finitecore-js(-pure)/es|stable|features/number/is-finitees.number.is-integercore-js(-pure)/es|stable|features/number/is-integeres.number.is-nancore-js(-pure)/es|stable|features/number/is-nanes.number.is-safe-integercore-js(-pure)/es|stable|features/number/is-safe-integeres.number.max-safe-integercore-js(-pure)/es|stable|features/number/max-safe-integeres.number.min-safe-integercore-js(-pure)/es|stable|features/number/min-safe-integeres.number.parse-floatcore-js(-pure)/es|stable|features/parse-floates.number.parse-intcore-js(-pure)/es|stable|features/parse-intes.number.to-fixedcore-js(-pure)/es|stable|features/number/to-fixedes.number.to-precisioncore-js(-pure)/es|stable|features/number/to-precisiones.parse-intcore-js(-pure)/es|stable|features/parse-intes.parse-floatcore-js(-pure)/es|stable|features/parse-float重点实现
TODO
# ECMAScript: Math
特性列表
分类 特性 路径 es.mathcore-js(-pure)/es|stable|features/mathes.math.acoshcore-js(-pure)/es|stable|features/math/acoshes.math.asinhcore-js(-pure)/es|stable|features/math/asinhes.math.atanhcore-js(-pure)/es|stable|features/math/atanhes.math.cbrtcore-js(-pure)/es|stable|features/math/cbrtes.math.clz32core-js(-pure)/es|stable|features/math/clz32es.math.coshcore-js(-pure)/es|stable|features/math/coshes.math.expm1core-js(-pure)/es|stable|features/math/expm1es.math.froundcore-js(-pure)/es|stable|features/math/froundes.math.hypotcore-js(-pure)/es|stable|features/math/hypotes.math.imulcore-js(-pure)/es|stable|features/math/imules.math.log10core-js(-pure)/es|stable|features/math/log10es.math.log1pcore-js(-pure)/es|stable|features/math/log1pes.math.log2core-js(-pure)/es|stable|features/math/log2es.math.signcore-js(-pure)/es|stable|features/math/signes.math.sinhcore-js(-pure)/es|stable|features/math/sinhes.math.tanhcore-js(-pure)/es|stable|features/math/tanhes.math.trunccore-js(-pure)/es|stable|features/math/trunc重点实现
TODO
# ECMAScript: Date
特性列表
分类 特性 路径 es.datecore-js/es|stable|features/datees.date.to-stringcore-js/es|stable|features/date/to-stringes.date.nowcore-js(-pure)/es|stable|features/date/nowes.date.to-iso-stringcore-js(-pure)/es|stable|features/date/to-iso-stringes.date.to-jsoncore-js(-pure)/es|stable|features/date/to-jsones.date.to-primitivecore-js(-pure)/es|stable|features/date/to-primitivees.date.get-yearcore-js(-pure)/es|stable|features/date/get-yeares.date.set-yearcore-js(-pure)/es|stable|features/date/set-yeares.date.to-gmt-stringcore-js(-pure)/es|stable|features/date/to-gmt-string重点实现
TODO
# ECMAScript: Promise
特性列表
分类 特性 路径 es.aggregate-errorcore-js(-pure)/es|stable|features/aggregate-errores.promisecore-js(-pure)/es|stable|features/promisees.promise.all-settledcore-js(-pure)/es|stable|features/promise/all-settledes.promise.anycore-js(-pure)/es|stable|features/promise/anyes.promise.finallycore-js(-pure)/es|stable|features/promise/finally重点实现
TODO
# ECMAScript: Symbol
特性列表
分类 特性 路径 es.symbolcore-js(-pure)/es|stable|features/symboles.symbol.async-iteratorcore-js(-pure)/es|stable|features/symbol/async-iteratores.symbol.descriptioncore-js/es|stable|features/symbol/descriptiones.symbol.has-instancecore-js(-pure)/es|stable|features/symbol/has-instancees.symbol.is-concat-spreadablecore-js(-pure)/es|stable|features/symbol/is-concat-spreadablees.symbol.iteratorcore-js(-pure)/es|stable|features/symbol/iteratores.symbol.matchcore-js(-pure)/es|stable|features/symbol/matches.symbol.replacecore-js(-pure)/es|stable|features/symbol/replacees.symbol.searchcore-js(-pure)/es|stable|features/symbol/searches.symbol.speciescore-js(-pure)/es|stable|features/symbol/specieses.symbol.splitcore-js(-pure)/es|stable|features/symbol/splites.symbol.to-primitivecore-js(-pure)/es|stable|features/symbol/to-primitivees.symbol.to-string-tagcore-js(-pure)/es|stable|features/symbol/to-string-tages.symbol.unscopablescore-js(-pure)/es|stable|features/symbol/unscopablescore-js(-pure)/es|stable|features/symbol/forcore-js(-pure)/es|stable|features/symbol/key-forcore-js(-pure)/es|stable|features/object/get-own-property-symbols重点实现
TODO
# ECMAScript: Collections
特性列表
分类 特性 路径 Map es.mapcore-js(-pure)/es|stable|features/mapSet es.setcore-js(-pure)/es|stable|features/setWeakMap es.weak-mapcore-js(-pure)/es|stable|features/weak-mapWeakSet es.weak-setcore-js(-pure)/es|stable|features/weak-set重点实现
TODO
# ECMAScript: Typed Arrays
特性列表
分类 特性 路径 es.array-buffercore-js/es|stable|features/array-bufferes.array-buffer.constructorcore-js/es|stable|features/array-buffer/constructores.array-buffer.is-viewcore-js/es|stable|features/array-buffer/is-viewes.array-buffer.slicecore-js/es|stable|features/array-buffer/slicees.data-viewcore-js/es|stable|features/data-viewes.typed-arraycore-js/es|stable|features/typed-arrayes.typed-array.int8-arraycore-js/es|stable|features/typed-array/int8-arrayes.typed-array.uint8-arraycore-js/es|stable|features/typed-array/uint8-arrayes.typed-array.uint8-clamped-arraycore-js/es|stable|features/typed-array/uint8-clamped-arrayes.typed-array.int16-arraycore-js/es|stable|features/typed-array/int16-arrayes.typed-array.uint16-arraycore-js/es|stable|features/typed-array/uint16-arrayes.typed-array.int32-arraycore-js/es|stable|features/typed-array/int32-arrayes.typed-array.uint32-arraycore-js/es|stable|features/typed-array/uint32-arrayes.typed-array.float32-arraycore-js/es|stable|features/typed-array/float32-arrayes.typed-array.float64-arraycore-js/es|stable|features/typed-array/float64-arrayes.typed-array.copy-withincore-js/es|stable|features/typed-array/copy-withines.typed-array.everycore-js/es|stable|features/typed-array/everyes.typed-array.fillcore-js/es|stable|features/typed-array/filles.typed-array.filtercore-js/es|stable|features/typed-array/filteres.typed-array.findcore-js/es|stable|features/typed-array/findes.typed-array.find-indexcore-js/es|stable|features/typed-array/find-indexes.typed-array.for-eachcore-js/es|stable|features/typed-array/for-eaches.typed-array.fromcore-js/es|stable|features/typed-array/fromes.typed-array.includescore-js/es|stable|features/typed-array/includeses.typed-array.index-ofcore-js/es|stable|features/typed-array/index-ofes.typed-array.iteratorcore-js/es|stable|features/typed-array/iteratores.typed-array.last-index-ofcore-js/es|stable|features/typed-array/last-index-ofes.typed-array.mapcore-js/es|stable|features/typed-array/mapes.typed-array.ofcore-js/es|stable|features/typed-array/ofes.typed-array.reducecore-js/es|stable|features/typed-array/reducees.typed-array.reduce-rightcore-js/es|stable|features/typed-array/reduce-rightes.typed-array.reversecore-js/es|stable|features/typed-array/reversees.typed-array.setcore-js/es|stable|features/typed-array/setes.typed-array.slicecore-js/es|stable|features/typed-array/slicees.typed-array.somecore-js/es|stable|features/typed-array/somees.typed-array.sortcore-js/es|stable|features/typed-array/sortes.typed-array.subarraycore-js/es|stable|features/typed-array/subarrayes.typed-array.to-locale-stringcore-js/es|stable|features/typed-array/to-locale-stringes.typed-array.to-stringcore-js/es|stable|features/typed-array/to-stringes.typed-array.atcore-js/es|stable|features/typed-array/at重点实现
TODO
# ECMAScript: Reflect
特性列表
分类 特性 路径 es.reflectcore-js(-pure)/es|stable|features/reflectes.reflect.applycore-js(-pure)/es|stable|features/reflect/applyes.reflect.constructcore-js(-pure)/es|stable|features/reflect/constructes.reflect.define-propertycore-js(-pure)/es|stable|features/reflect/define-propertyes.reflect.delete-propertycore-js(-pure)/es|stable|features/reflect/delete-propertyes.reflect.getcore-js(-pure)/es|stable|features/reflect/getes.reflect.get-own-property-descriptorcore-js(-pure)/es|stable|features/reflect/get-own-property-descriptores.reflect.get-prototype-ofcore-js(-pure)/es|stable|features/reflect/get-prototype-ofes.reflect.hascore-js(-pure)/es|stable|features/reflect/hases.reflect.is-extensiblecore-js(-pure)/es|stable|features/reflect/is-extensiblees.reflect.own-keyscore-js(-pure)/es|stable|features/reflect/own-keyses.reflect.prevent-extensionscore-js(-pure)/es|stable|features/reflect/prevent-extensionses.reflect.setcore-js(-pure)/es|stable|features/reflect/setes.reflect.set-prototype-ofcore-js(-pure)/es|stable|features/reflect/set-prototype-of重点实现
TODO
# ECMAScript: JSON
特例列表
分类 特性 路径 es.json.to-string-tagcore-js(-pure)/es|stable|features/json/to-string-tages.json.stringifycore-js(-pure)/es|stable|features/json/stringify重点实现
TODO
# ECMAScript: globalThis
特性列表
分类 特性 路径 es.global-thiscore-js(-pure)/es|stable|features/global-this重点实现
文件
core-js/packages/core-js/internals/global.js定义了全局对象的实现,代码如下:var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 module.exports = // eslint-disable-next-line es/no-global-this -- safe check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || // eslint-disable-next-line no-restricted-globals -- safe check(typeof self == 'object' && self) || check(typeof global == 'object' && global) || // eslint-disable-next-line no-new-func -- fallback (function () { return this; })() || Function('return this')();1
2
3
4
5
6
7
8
9
10
11
12
13
14可以看到,定义全局对象的过程有以下特点:
判断全局对象的先后顺序
依次是:
globalThis、window、self、global、自定义方法获取。自定义方法获取全局对象
用立即执行函数获取全局对象,优先使用
(function () { return this; })(),其次使用Function('return this')()。判断全局对象是否有效
check函数用于校验对象是否是有效的全局对象,判断该对象的Math属性是否和全局的Math变量一致。
# ECMAScript 提案的补丁
# Stage 4 proposals
特性列表
分类 特性 路径 globalThises.global-thiscore-js/proposals/global-thiscore-js(-pure)/es|stable|features/global-thisString#matchAlles.string.match-allcore-js/proposals/string-match-allcore-js/es|stable|features/string/match-allString#replaceAlles.string.replace-allcore-js/proposals/string-replace-allcore-js/es|stable|features/string/replace-allPromise.allSettledes.promise.all-settledcore-js/proposals/promise-all-settledcore-js(-pure)/es|stable|features/promise/all-settledPromise.anyes.promise.anycore-js/proposals/promise-anycore-js(-pure)/es|stable|features/promise/anyPromise.anyes.aggregate-errorcore-js(-pure)/es|stable|features/aggregate-errorObject.prototype.hasOwnPropertyes.object.has-owncore-js/proposals/accessible-object-hasownpropertycore-js(-pure)/es|stable|features/object/has-ownes.array.ates.string.at-alternativeRelative indexing method core-js/proposals/relative-indexing-methodRelative indexing method es.typed-array.atcore-js(-pure)/es|stable|features/array/atRelative indexing method core-js(-pure)/es|stable|features/string/atRelative indexing method es.typed-array.atcore-js(-pure)/es|stable|features/typed-array/at重点实现
TODO
# Stage 3 proposals
特性列表
分类 特性 路径 esnext.array.find-lastcore-js(-pure)/features(/virtual)/array/find-lastesnext.array.find-last-indexcore-js(-pure)/features(/virtual)/array/find-last-indexesnext.typed-array.find-lastcore-js/features/typed-array/find-lastesnext.typed-array.find-last-indexcore-js/features/typed-array/find-last-index重点实现
TODO
# Stage 2 proposals
特性列表
分类 特性 路径 Iterator helpers core-js/proposals/iterator-helpersIterator helpers esnext.async-iterator.constructorIterator helpers esnext.async-iterator.as-indexed-pairscore-js(-pure)/features/async-iterator/as-indexed-pairsIterator helpers esnext.async-iterator.dropcore-js(-pure)/features/async-iterator/dropIterator helpers esnext.async-iterator.everycore-js(-pure)/features/async-iterator/everyIterator helpers esnext.async-iterator.filtercore-js(-pure)/features/async-iterator/filterIterator helpers esnext.async-iterator.findcore-js(-pure)/features/async-iterator/findIterator helpers esnext.async-iterator.flat-mapcore-js(-pure)/features/async-iterator/flat-mapIterator helpers esnext.async-iterator.for-eachcore-js(-pure)/features/async-iterator/for-eachIterator helpers esnext.async-iterator.fromcore-js(-pure)/features/async-iterator/fromIterator helpers esnext.async-iterator.mapcore-js(-pure)/features/async-iterator/mapIterator helpers esnext.async-iterator.reducecore-js(-pure)/features/async-iterator/reduceIterator helpers esnext.async-iterator.somecore-js(-pure)/features/async-iterator/someIterator helpers esnext.async-iterator.takecore-js(-pure)/features/async-iterator/takeIterator helpers esnext.async-iterator.to-arraycore-js(-pure)/features/async-iterator/to-arrayIterator helpers esnext.iterator.constructorIterator helpers esnext.iterator.as-indexed-pairscore-js(-pure)/features/iterator/as-indexed-pairsIterator helpers esnext.iterator.dropcore-js(-pure)/features/iterator/dropIterator helpers esnext.iterator.everycore-js(-pure)/features/iterator/everyIterator helpers esnext.iterator.filtercore-js(-pure)/features/iterator/filterIterator helpers esnext.iterator.findcore-js(-pure)/features/iterator/findIterator helpers esnext.iterator.flat-mapcore-js(-pure)/features/iterator/flat-mapIterator helpers esnext.iterator.for-eachcore-js(-pure)/features/iterator/for-eachIterator helpers esnext.iterator.fromcore-js(-pure)/features/iterator/fromIterator helpers esnext.iterator.mapcore-js(-pure)/features/iterator/mapIterator helpers esnext.iterator.reducecore-js(-pure)/features/iterator/reduceIterator helpers esnext.iterator.somecore-js(-pure)/features/iterator/someIterator helpers esnext.iterator.takecore-js(-pure)/features/iterator/takeIterator helpers esnext.iterator.to-arraycore-js(-pure)/features/iterator/to-arrayesnext.set.difference` New Set methods core-js/proposals/set-methodsNew Set methods esnext.set.intersectioncore-js(-pure)/features/set/intersectionNew Set methods esnext.set.is-disjoint-fromcore-js(-pure)/features/set/is-disjoint-fromNew Set methods esnext.set.is-subset-ofcore-js(-pure)/features/set/is-subset-ofNew Set methods esnext.set.is-superset-ofcore-js(-pure)/features/set/is-superset-ofNew Set methods esnext.set.symmetric-differencecore-js(-pure)/features/set/symmetric-differenceNew Set methods esnext.set.unioncore-js(-pure)/features/set/unionMap.prototype.emplace esnext.map.emplacecore-js(-pure)/features/map/emplaceMap.prototype.emplace esnext.weak-map.emplacecore-js(-pure)/features/weak-map/emplaceArray.isTemplateObject esnext.array.is-template-objectcore-js/proposals/array-is-template-objectcore-js(-pure)/features/array/is-template-objectesnext.symbol.disposecore-js(-pure)/features/symbol/disposeesnext.symbol.async-disposecore-js(-pure)/features/symbol/async-disposeesnext.symbol.metadatacore-js/proposals/decoratorscore-js(-pure)/features/symbol/metadata重点实现
TODO
# Stage 1 proposals
特性列表
分类 特性 路径 esnext.observablecore-js/proposals/observablecore-js(-pure)/features/observableesnext.symbol.observablecore-js(-pure)/features/symbol/observableesnext.set.add-allcore-js(-pure)/features/set/add-allesnext.set.delete-allcore-js(-pure)/features/set/delete-allesnext.set.everycore-js(-pure)/features/set/everyesnext.set.filtercore-js(-pure)/features/set/filteresnext.set.findcore-js(-pure)/features/set/findesnext.set.joincore-js(-pure)/features/set/joinesnext.set.mapcore-js(-pure)/features/set/mapesnext.set.reducecore-js(-pure)/features/set/reduceesnext.set.somecore-js(-pure)/features/set/someesnext.map.delete-allcore-js(-pure)/features/map/delete-allesnext.map.everycore-js(-pure)/features/map/everyesnext.map.filtercore-js(-pure)/features/map/filteresnext.map.findcore-js(-pure)/features/map/findesnext.map.find-keycore-js(-pure)/features/map/find-keyesnext.map.group-bycore-js(-pure)/features/map/group-byesnext.map.includescore-js(-pure)/features/map/includesesnext.map.key-bycore-js(-pure)/features/map/key-byesnext.map.key-ofcore-js(-pure)/features/map/key-ofesnext.map.map-keyscore-js(-pure)/features/map/map-keysesnext.map.map-valuescore-js(-pure)/features/map/map-valuesesnext.map.mergecore-js(-pure)/features/map/mergeesnext.map.reducecore-js(-pure)/features/map/reduceesnext.map.somecore-js(-pure)/features/map/someesnext.map.updatecore-js(-pure)/features/map/updateesnext.weak-set.add-allcore-js(-pure)/features/weak-set/add-allesnext.weak-set.delete-allcore-js(-pure)/features/weak-set/delete-allesnext.weak-map.delete-allcore-js(-pure)/features/weak-map/delete-allesnext.set.ofcore-js(-pure)/features/weak-set/ofesnext.set.fromcore-js(-pure)/features/weak-set/fromesnext.map.ofcore-js(-pure)/features/weak-map/ofesnext.map.fromcore-js(-pure)/features/weak-map/fromesnext.weak-set.ofcore-js(-pure)/features/weak-set/ofesnext.weak-set.fromcore-js(-pure)/features/weak-set/fromesnext.weak-map.ofcore-js(-pure)/features/weak-map/ofesnext.weak-map.fromcore-js(-pure)/features/weak-map/fromesnext.composite-keycore-js/proposals/keys-compositioncore-js(-pure)/features/composite-keyesnext.composite-symbolcore-js(-pure)/features/composite-symbolesnext.array.filter-rejectcore-js(-pure)/features/weak-set/fromesnext.esnext.array.filter-rejectcore-js/proposals/array-filteringcore-js(-pure)/features/array(/virtual)/filter-rejectesnext.typed-array.filter-rejectcore-js/features/typed-array/filter-rejectesnext.array.group-bycore-js/proposals/array-groupingcore-js(-pure)/features/array(/virtual)/group-byesnext.typed-array.group-bycore-js/features/typed-array/group-byesnext.array.unique-bycore-js/proposals/array-uniquecore-js(-pure)/features/array(/virtual)/unique-byesnext.typed-array.unique-bycore-js/features/typed-array/unique-byesnext.array.last-itemcore-js/proposals/array-lastcore-js/features/array/last-itemesnext.array.last-indexcore-js/features/array/last-indexesnext.number.rangecore-js/proposals/number-rangecore-js(-pure)/features/bigint/rangeesnext.bigint.rangecore-js(-pure)/features/number/rangeesnext.number.from-stringcore-js/proposals/number-from-stringcore-js(-pure)/features/number/from-stringesnext.math.clampcore-js(-pure)/features/math/clampesnext.math.deg-per-radcore-js(-pure)/features/math/deg-per-radesnext.math.degreescore-js(-pure)/features/math/degreesesnext.math.fscalecore-js(-pure)/features/math/fscaleesnext.math.rad-per-degcore-js(-pure)/features/math/rad-per-degesnext.math.radianscore-js(-pure)/features/math/radiansesnext.math.scalecore-js(-pure)/features/math/scaleesnext.math.signbitcore-js/proposals/math-signbitcore-js(-pure)/features/math/signbitesnext.string.code-pointscore-js/proposals/string-code-pointscore-js(-pure)/features/string/code-pointsesnext.symbol.matchercore-js/proposals/pattern-matchingcore-js(-pure)/features/symbol/matcheresnext.math.seeded-prngcore-js/proposals/seeded-randomcore-js(-pure)/features/math/seeded-prngcore-js/proposals/object-iterationesnext.object.iterate-keyscore-js(-pure)/features/object/iterate-keysesnext.object.iterate-valuescore-js(-pure)/features/object/iterate-valuesesnext.object.iterate-entriescore-js(-pure)/features/object/iterate-entriesesnext.promise.trycore-js/proposals/promise-trycore-js(-pure)/features/promise/try重点实现
TODO
# Stage 0 proposals
特性列表
分类 特性 路径 URLesnext.string.atcore-js/proposals/string-atcore-js(-pure)/features/string/atcore-js(-pure)/features/string/virtual/core-js/proposals/efficient-64-bit-arithmeticesnext.math.iaddhcore-js(-pure)/features/math/iaddhesnext.math.isubhcore-js(-pure)/features/math/isubhesnext.math.imulhcore-js(-pure)/features/math/imulhesnext.math.umulhcore-js(-pure)/features/math/umulh重点实现
TODO
# Pre-stage 0 proposals
特性列表
分类 特性 路径 core-js/proposals/reflect-metadataesnext.reflect.define-metadatacore-js(-pure)/features/reflect/define-metadataesnext.reflect.delete-metadatacore-js(-pure)/features/reflect/delete-metadataesnext.reflect.get-metadatacore-js(-pure)/features/reflect/get-metadataesnext.reflect.get-metadata-keyscore-js(-pure)/features/reflect/get-metadata-keysesnext.reflect.get-own-metadatacore-js(-pure)/features/reflect/get-own-metadataesnext.reflect.get-own-metadata-keyscore-js(-pure)/features/reflect/get-own-metadata-keysesnext.reflect.has-metadatacore-js(-pure)/features/reflect/has-metadataesnext.reflect.has-own-metadatacore-js(-pure)/features/reflect/has-own-metadataesnext.reflect.metadatacore-js(-pure)/features/reflect/metadata重点实现
TODO
# WEB 标准 API 的补丁
# 特性列表
| 分类 | 模块 | 特性 | 路径 |
|---|---|---|---|
web.timers | setTimeout | core-js(-pure)/stable|features/set-timeout | |
web.timers | setInterval | core-js(-pure)/stable|features/set-interval | |
web.immediate | setImmediate | core-js(-pure)/stable|features/set-immediate | |
web.immediate | clearImmediate | core-js(-pure)/stable|features/clear-immediate | |
web.queue-microtask | queueMicrotask | core-js/web/queue-microtaskcore-js(-pure)/stable|features/queue-microtask | |
web.url | |||
web.url.to-json | |||
web.url-search-params | |||
web.dom-collections.iterator | |||
web.dom-collections.for-each | |||
web.dom-collections.iterator | core-js(-pure)/stable|features/dom-collections/iterator | ||
web.dom-collections.for-each | core-js/stable|features/dom-collections/for-each | ||
core-js-pure/es|stable|features/is-iterable | |||
core-js-pure/es|stable|features/get-iterator | |||
core-js-pure/es|stable|features/get-iterator-method |
core-js 中和 WEB 标准相关的 API 实现,定义在 core-js/packages/core-js/web/ 目录下,并实现了以下 API:
# dom-collections
介绍
dom-collections 表示 HTML 中获取 DOM 节点集的一系列方法。
下表是文件
core-js/packages/core-js/internals/dom-iterables.js列举的 dom-collections:dom-collection 作用 CSSRuleListCSSStyleDeclarationCSSValueListClientRectListDOMRectListDOMStringListDOMTokenListDataTransferItemListFileListHTMLAllCollectionHTMLCollectionHTMLFormElementHTMLSelectElementMediaListMimeTypeArrayNamedNodeMapNodeListPaintRequestListPluginPluginArraySVGLengthListSVGNumberListSVGPathSegListSVGPointListSVGStringListSVGTransformListSourceBufferListStyleSheetListTextTrackCueListTextTrackListTouchList补丁
core-js 为上述 dom-collection 方法添加了一系列补丁,目的是为其确保实现了
for-each/iterator系列方法:require('../modules/web.dom-collections.for-each'); // 确保 for-each 实现 require('../modules/web.dom-collections.iterator'); // 确保 iterator 实现 var path = require('../internals/path'); module.exports = path;1
2
3
4
5for-each
core-js 在文件
core-js/packages/core-js/internals/array-iteration.js定义了和数组相关的多个方法的补丁,总体来说,forEach/map/filter/some/every/find/findIndex/filterOut均用for循环实现。var global = require('../internals/global'); // 全局对象 var DOMIterables = require('../internals/dom-iterables'); var forEach = require('../internals/array-for-each'); // core-js 自身实现的 forEach var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); // COLLECTION_NAME: CSSRuleList/CSSStyleDeclaration/CSSValueList/... for (var COLLECTION_NAME in DOMIterables) { var Collection = global[COLLECTION_NAME]; var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); } catch (error) { CollectionPrototype.forEach = forEach; } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16从源码可以看出,core-js 会给浏览器支持的 dom-collections API,以
Object.defineProperty或直接赋值的方式提供forEach方法实现。iterator
core-js 在
core-js/packages/core-js/modules/web.dom-collections.iterator.js文件定义了对 iterator 的实现。TODO
# immediate
immediate介绍
TODO
兼容性判断
core-js 提供了
setImmediate/clearImmediate的兼容性实现。在文件
core-js/packages/core-js/modules/web.immediate.js中可以看到,在实现setImmediate时,做出了以下处理:如果
setImmediate/clearImmediate均已被支持,则不再处理如果
setImmediate/clearImmediate有任何一个没有被支持,则手动实现setImmediate/clearImmediate,并赋值到全局对象var FORCED = !global.setImmediate || !global.clearImmediate; // http://w3c.github.io/setImmediate/ $({ global: true, bind: true, enumerable: true, forced: FORCED }, { // `setImmediate` method // http://w3c.github.io/setImmediate/#si-setImmediate setImmediate: task.set, // `clearImmediate` method // http://w3c.github.io/setImmediate/#si-clearImmediate clearImmediate: task.clear });1
2
3
4
5
6
7
8
9
10
11
补丁
set = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); // 将 fn 推入队列 queue[++counter] = function () { (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); }; // 将当前处理逻辑的索引注册到待执行函数 // 待执行函数根据不同环境有不同实现 defer(counter); // 返回数字形式的“句柄” return counter; }; clear = function clearImmediate(id) { delete queue[id]; };1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21通过自定义的
setImmediate方法,做到了:- 维护一个执行队列,按顺序执行处理逻辑,用
queue数组维护 - 将当前处理逻辑的索引注册到待执行函数,用
defer方法实现,defer会根据不同环境有不同的实现 - 最终返回数字形式的“句柄”
defer 的实现依据以下先后顺序:
process.nextTick: 如果是 Node 环境Dispatch.now: 如果是 Sphere 游戏引擎环境MessageChannel: 如果不是 iOS 环境,且支持 MessageChannelpostMessage: 如果支持 postMessagecreateElement('script')的onreadystatechange事件setTimeout
- 维护一个执行队列,按顺序执行处理逻辑,用
# queue-microtask
介绍
https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_DOM_API/Microtask_guide
补丁
TODO
# timers
介绍
timers 指的就是
setTimeout/setInterval,二者的使用方式如下:setTimeout(handler[, delay, arg1, arg2, ...])setInterval(handler, delay, [arg1, arg2, ...])
补丁
core-js 对 timers 的补丁位于
core-js/packages/core-js/modules/web.timers.js,IE9 及以下版本会强制使用 core-js 自定义的实现。实现代码:
var $ = require('../internals/export'); var global = require('../internals/global'); var userAgent = require('../internals/engine-user-agent'); var slice = [].slice; var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check var wrap = function (scheduler) { return function (handler, timeout /* , ...arguments */) { var boundArgs = arguments.length > 2; var args = boundArgs ? slice.call(arguments, 2) : undefined; return scheduler( boundArgs ? function () { (typeof handler == 'function' ? handler : Function(handler)).apply(this, args); } : handler, timeout ); }; }; // ie9- setTimeout & setInterval additional parameters fix // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers $({ global: true, bind: true, forced: MSIE }, { // `setTimeout` method // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout setTimeout: wrap(global.setTimeout), // `setInterval` method // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval setInterval: wrap(global.setInterval) });1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35可以看到,如果传入的
handler不是函数,则用Function(handler)).apply(this, args)的方式调用
# url
core-js 对 url 的兼容性支持体现在三个子功能: URL 构造函数、URL.prototype.toJSON、URLSearchParams 构造函数。
对WAHTWG标准的兼容性判断
core-js/packages/core-js/internals/native-url.js文件描述了如何判断运行环境是否支持标准的URLSearchParams:var fails = require('../internals/fails'); var wellKnownSymbol = require('../internals/well-known-symbol'); var IS_PURE = require('../internals/is-pure'); var ITERATOR = wellKnownSymbol('iterator'); // 返回值描述了宿主环节是否已支持 URLSearchParams module.exports = !fails(function () { var url = new URL('b?a=1&b=2&c=3', 'http://a'); var searchParams = url.searchParams; var result = ''; url.pathname = 'c%20d'; searchParams.forEach(function (value, key) { searchParams['delete']('b'); result += key + value; }); return (IS_PURE && !url.toJSON) || !searchParams.sort || url.href !== 'http://a/c%20d?a=1&c=3' || searchParams.get('c') !== '3' || String(new URLSearchParams('?a=1')) !== 'a=1' || !searchParams[ITERATOR] // throws in Edge || new URL('https://a@b').username !== 'a' || new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b' // not punycoded in Edge || new URL('http://тест').host !== 'xn--e1aybc' // not escaped in Chrome 62- || new URL('http://a#б').hash !== '#%D0%B1' // fails in Chrome 66- || result !== 'a1c3' // throws in Safari || new URL('http://x', undefined).host !== 'x'; });1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34fails方法接收一个执行函数,并在内部使用try...catch...执行该函数,若执行失败(有报错情况),fails()方法返回true,否则返回false,这是fails()方法的实现:module.exports = function (exec) { try { return !!exec(); } catch (error) { return true; } };1
2
3
4
5
6
7如果运行时环境不支持标准的
url定义,core-js 会提供自己的 API 实现url的一些特性,如:URL构造函数的补丁定义在文件core-js/packages/core-js/modules/web.url.jsURLSearchParams的补丁定义在文件core-js/packages/core-js/modules/web.url-search-params.js
对 url 的统一处理
core-js/packages/core-js/web/url.js文件提供了对 url 各个特征的处理:require('../modules/web.url'); require('../modules/web.url.to-json'); require('../modules/web.url-search-params');1
2
3web.url.js文件提供了基于 WHATWG 标准的各个特征的实现。web.url.to-json提供了URL.prototype.toJSON的实现。web.url-search-params提供了URLSearchParams的实现。URL构造函数TODO
URLSearchParams介绍
URLSearchParams接口定义了一些实用的方法来处理 URL 的查询字符串,比如:var paramsString = "q=URLUtils.searchParams&topic=api" var searchParams = new URLSearchParams(paramsString); for (let p of searchParams) { console.log(p); } // [ 'q', 'URLUtils.searchParams' ],[ 'topic', 'api' ] searchParams.has("topic") === true; // true searchParams.get("topic") === "api"; // true searchParams.getAll("topic"); // ["api"] searchParams.get("foo") === null; // true searchParams.append("topic", "webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" searchParams.set("topic", "More webdev"); searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" searchParams.delete("topic"); searchParams.toString(); // "q=URLUtils.searchParams"1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17根据WHATWG的标准,core-js提供了不满足该标准的运行环境下的补丁。
补丁
TODO
URL.prototype.toJSON有独立的文件
core-js/packages/core-js/modules/web.url.to-json.js描述了该实现:'use strict'; var $ = require('../internals/export'); // `URL.prototype.toJSON` method // https://url.spec.whatwg.org/#dom-url-tojson $({ target: 'URL', proto: true, enumerable: true }, { toJSON: function toJSON() { return URL.prototype.toString.call(this); } });1
2
3
4
5
6
7
8
9
10可以看到,
toJSON的实现和toString一致,注意,这里并没有涉及兼容性的处理,是因为toString方法在此之前已经被兼容性处理过了。不过,由于
web.url.js也提供了toJSON的实现,这一步并没有必要了。
# 缺失的补丁
BigInt介绍
TODO
补丁缺失的原因
TODO
Proxy介绍
TODO
补丁缺失的原因
TODO
String#normalize介绍
TODO
补丁缺失的原因
TODO
Intl介绍
TODO
补丁缺失的原因
TODO
window.fetch介绍
TODO
补丁缺失的原因
TODO