JS :Polyfill是什么意思
1.什么是ployfill
Polyfill 是一块代码(通常是 Web 上的 JavaScript),用来为旧浏览器提供它没有原生支持的较新的功能。即Polyfill是一个js库,主要抚平不同浏览器之间对js实现的差异。比如,html5的storage(session,local), 不同浏览器,不同版本,有些支持,有些不支持。
相当于打补丁, web 发展太快,随着 web 需求不断增长,而且要求越来越高,这是很多浏览器跟不上 js 的脚步了。所以少不了 polyfill 来打补丁。
如:document.querySelectorAll()现在大多数浏览器都已经支持该方法,但是仍然存在一些比较老的版本的浏览器不支持该方法,此时如果写一个库,通过对该库的引用,从而使得浏览器可以和其他浏览器一样使用该方法,此时这个库就是polyfill。
polyfill的本质是抹平不同浏览器的api之间的差异,而不是自己实现新的api。
2.例如:
polyfill.js:
if (Promise && !Promise.newallSettled) {
Promise.newallSettled = function (promises) {
return Promise.all(promises.map(function (promise) {
return promise.then(function (value) {
return { state: 'fulfilled', value: value };
}).catch(function (reason) {
return { state: 'rejected', reason: reason };
});
}));
};
}
<script src="./polyfill.js" ></script>
<script>
const delay = n => new Promise(resolve => setTimeout(resolve, n));
const promises = [
delay(1).then(() => 1),
delay(2).then(() => 2),
Promise.reject(3),
]
//newallSettled实现了allSettled
Promise.newallSettled(promises).then(values => console.log(values))
</script>
参考链接:https://www.jianshu.com/p/7562b8b589f3
https://blog.csdn.net/weixin_47450807/article/details/123080204
查看10道真题和解析