Ikeq ChengIkeq Cheng

The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts.

关于Shim和polyfill

Aug 14, 2014Programming480 words in 2 min

在计算机编程,特别是javascript中这两个词经常出现,比如:


Shim

wikipedia:

In computer programming, a shim is a small library that transparently intercepts API calls and changes the arguments passed, handles the operation itself, or redirects the operation elsewhere. Shims typically come about when the behavior of an API changes, thereby causing compatibility issues for older applications which still rely on the older functionality. In such cases, the older API can still be supported by a thin compatibility layer on top of the newer code.

shim即垫片,在计算机编程中指代一类库,可以透明拦截API调用、改变参数传递、处理整个操作,或重定向操作。垫片常用于向上兼容,使得开发者可以在当时的应用程序环境中使用即将发布的、新的语言特性,就好像浏览器原生支持一样。

例如es6中加入的类定义语法

1
2
3
4
5
6
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}

想要现在使用此语法,就需要借助上文提到的es6-shim

类似的概念还有shiv。

Polyfil

wikipedia:

In web development, a polyfill (or polyfiller) is downloadable code which provides facilities that are not built into a web browser. It implements technology that a developer expects the browser to provide natively, providing a more uniform API landscape. For example, many features of HTML5 are not supported by versions of Internet Explorer older than version 8 or 9, but can be used by web pages if those pages install a polyfill.

polyfill即聚乙烯填充物,在web开发中,也指代一类库,它提供了开发者期望浏览器能够原生提供的功能。比如虽然很多HTML5的新特性在低版本IE中并不支持,但如果引入特定的polyfill库,就可以使用这些新特性,就好像浏览器原生支持一样。

例如低版本IE不提供JSON对象,可以简单的通过evalFunction实现。

1
2
3
4
5
6
7
// json polyfill

JSON = {
parse: function(string) {
return new Function('return ' + string);
}
}

[扩展阅读]

Buy me a cup of milk 🥛.