如何在 JavaScript 中使用 polyfill?
JavaScript 的开发人员总是不断向 JavaScript 语言添加新功能,以提高性能并添加更好的功能。有时,旧浏览器版本不支持新功能。
例如,ES7中引入了指数运算符,对象中的尾随逗号在ES7中也有效。现在,在开发应用程序时,我们在应用程序中添加了指数运算符。它将适用于较新版本的浏览器,但如果有人使用非常旧版本的浏览器,他们可能会收到错误,例如浏览器引擎不支持指数运算符。
所以,我们可以使用polyfill来避免这种错误。让我们把polyfill这个词分成两部分来理解它的含义。 Poly意味着很多,fill意味着填补空白。这意味着如果浏览器不支持 JavaScript 的默认功能,则需要通过多种技术来填补浏览器功能的空白。
有两种方法可以解决浏览器不支持功能的问题。一个是polyfill,另一个是transpiler。转译器将代码转换为较低版本,以便浏览器可以支持它。例如,我们可以用 ES7 版本的 JavaScript 编写代码,然后使用转译器将其转换为 ES6 或 ES5,以使其被旧浏览器支持。
在这里,我们将学习使用 polyfill 概念的不同示例。
语法
用户可以按照以下语法使用polyfill概念手动实现JavaScript方法。
String.prototype.method_name = function (params) { // implement the code for the method // use this keyword to access the reference object }
我们已将方法添加到上述语法中的字符串原型中。 method_name 表示方法名称。我们将带有多个参数的函数分配给该方法。
示例 1(不带 polyfill 的 Includes() 方法)
在下面的示例中,我们使用了 String 对象的内置 contains() 方法。我们已经定义了字符串并使用includes()方法来检查字符串是否包含特定单词或子字符串。
<html> <body> <h2>Using the <i>includes() method without polyfill </i> in JavaScript</h2> <div id = "content"> </div> <script> let content = document.getElementById('content'); let str = "You are welcome on TutorialsPoint's website. Hello users! How are you?"; let isWelcome = str.includes('welcome'); content.innerHTML += "The original string: " + str + "<br>"; content.innerHTML += "The string includes welcome word? " + isWelcome + "<br>"; let isJavaScript = str.includes('javaScript'); content.innerHTML += "The string includes JavaScript word? " + isJavaScript + "<br>"; </script> </body> </html>
示例 2(带有 polyfill 的 Includes() 方法)
在上面的例子中,我们使用了内置的includes()方法。在这个例子中,我们将为includes()方法定义polyfill。如果任何浏览器不支持includes()方法,它将执行用户定义的includes()方法。
这里,我们将includes()方法添加到字符串对象的原型中。在函数中,如果搜索字符串是正则表达式类型,我们会抛出错误。另外,“pos”参数是一个选项,因此如果用户不传递它,则将其视为零。最后,使用indexof()方法检查字符串是否包含该单词,并根据该结果返回一个布尔值。
<html> <body> <h2>Using the <i>includes() method with polyfill </i> in JavaScript</h2> <div id = "content"> </div> <script> let content = document.getElementById('content'); String.prototype.includes = function (str, pos) { // first, check whether the first argument is a regular expression if (str instanceof RegExp) { throw Error("Search string can't be an instance of regular expression"); } // second parameter is optional. So, if it isn't passed as an argument, consider it zero if (pos === undefined) { pos = 0; } content.innerHTML += "The user-defined includes method is invoked! <br>" // check if the index of the string is greater than -1. If yes, string includes the search string. return this.indexOf(str, pos) !== -1; }; let str = "This is a testing string. Use this string to test includes method."; content.innerHTML += `The original string is "` + str +`" <br>`; let isTesting = str.includes('testing'); content.innerHTML += "The string includes testing word? " + isTesting + "<br>"; let isYour = str.includes('your'); content.innerHTML += "The string includes your word? " + isYour + "<br>"; </script> </body> </html>
示例3(为filter()方法实现polyfill)
我们在下面的示例中为filter()方法实现了polyfill。我们首先确保引用数组不为空并且回调是一种函数。之后,我们迭代数组并为每个数组值执行回调函数。如果回调函数返回 true,我们将其推送到输出数组。最后,我们返回包含过滤值的输出数组
<html> <body> <h2>Using the <i> filter() method with polyfill </i> in JavaScript</h2> <div id = "content"> </div> <script> let content = document.getElementById('content'); Array.prototype.filter = function (callback) { // check if the reference array is not null if (this === null) throw new Error; // check that callback is a type of function if (typeof callback !== "function") throw new Error; var output = []; // iterate through array for (var k = 0; k < this.length; k++) { // get value from index k var val = this[k]; // call the callback function and, based on a returned boolean value, push the array value in the output array if (callback.call(this, val, k)) { output.push(val); } } return output; }; function getDivisibleBy10(val, k) { // return true if val is divisible by 10. if (val % 10 == 0) { return true; } return false; } let array = [10, 20, 40, 65, 76, 87, 90, 80, 76, 54, 32, 23, 65, 60]; let filtered = array.filter(getDivisibleBy10); content.innerHTML += "The original array is " + JSON.stringify(array) + "<br>"; content.innerHTML += "The filtered array is " + JSON.stringify(filtered) + "<br>"; </script> </body> </html>
本教程教我们如何实现includes() 和filter() 方法的polyfill。但是,用户可以使用 if-else 语句来检查浏览器是否支持特定方法。如果没有,则执行用户定义的方法,否则执行内置方法。
以上是如何在 JavaScript 中使用 polyfill?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

本文讨论了在浏览器中优化JavaScript性能的策略,重点是减少执行时间并最大程度地减少对页面负载速度的影响。

本文讨论了使用浏览器开发人员工具的有效JavaScript调试,专注于设置断点,使用控制台和分析性能。

本文说明了如何使用源地图通过将其映射回原始代码来调试JAVASCRIPT。它讨论了启用源地图,设置断点以及使用Chrome DevTools和WebPack之类的工具。

本文探讨了Java收藏框架的有效使用。 它强调根据数据结构,性能需求和线程安全选择适当的收集(列表,设置,地图,队列)。 通过高效优化收集用法

掌握了入门级TypeScript教程后,您应该能够在支持TypeScript的IDE中编写自己的代码,并将其编译成JavaScript。本教程将深入探讨TypeScript中各种数据类型。 JavaScript拥有七种数据类型:Null、Undefined、Boolean、Number、String、Symbol(ES6引入)和Object。TypeScript在此基础上定义了更多类型,本教程将详细介绍所有这些类型。 Null数据类型 与JavaScript一样,TypeScript中的null

本教程将介绍如何使用 Chart.js 创建饼图、环形图和气泡图。此前,我们已学习了 Chart.js 的四种图表类型:折线图和条形图(教程二),以及雷达图和极地区域图(教程三)。 创建饼图和环形图 饼图和环形图非常适合展示某个整体被划分为不同部分的比例。例如,可以使用饼图展示野生动物园中雄狮、雌狮和幼狮的百分比,或不同候选人在选举中获得的投票百分比。 饼图仅适用于比较单个参数或数据集。需要注意的是,饼图无法绘制值为零的实体,因为饼图中扇形的角度取决于数据点的数值大小。这意味着任何占比为零的实体
