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

如何在 JavaScript 中使用 polyfill?

王林
王林轉載
2023-08-26 09:05:021726瀏覽

如何在 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刪除