首页  >  文章  >  web前端  >  如何在 JavaScript 中使用 polyfill?

如何在 JavaScript 中使用 polyfill?

王林
王林转载
2023-08-26 09:05:021727浏览

如何在 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中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除