如何在JavaScript中使用polyfill?
JavaScript 的開發者們不斷向 JavaScript 語言新增新特性,以提高效能並新增更好的功能。有時,新特性並不受舊版瀏覽器的支援。
例如,指數運算子是在 ES7 中引入的,物件中的尾隨逗號在 ES7 中也是有效的。現在,在開發應用程式時,我們使用了指數運算子。它可以在較新版本的瀏覽器中工作,但如果有人使用的是非常舊版本的瀏覽器,他們可能會遇到錯誤,例如瀏覽器引擎不支援指數運算子。
因此,我們可以使用 *polyfill* 來避免此類錯誤。讓我們透過將 polyfill 這個詞分解成兩部分來理解它的含義。Poly 意思是多個,fill 意思是填充。這意味著如果瀏覽器不支援 JavaScript 的預設特性,則可以使用多種技術來填補瀏覽器中特性的空白。
解決瀏覽器不支援特性的問題,有兩種方法。一種是 polyfill,另一種是 transpiler。transpiler 將程式碼轉換為較低版本,以便瀏覽器可以支援它。例如,我們可以在 ES7 版本的 JavaScript 中編寫程式碼,並使用 transpiler 將其轉換為 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 物件的內建 includes() 方法。我們定義了字串並使用 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 語句來檢查瀏覽器是否支援特定方法。如果不支援,則執行使用者定義的方法,否則執行內建方法。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP