提供某些瀏覽器或環境本身不支援的功能的程式碼。簡單來說,就是瀏覽器後備。
在為call()、apply()和bind()方法編寫polyfill之前,請檢查call、apply和bind的功能。
let details = { name: 'Manoj', location: 'Chennai' } let getDetails = function (...args) { return `${this.name} from ${this.location}${args.join(', ') ? `, ${args.join(', ')}` : ''}`; }
1。呼叫方式:
讓我們為call()建立一個polyfill。我們將向 Function.prototype 新增自訂 call 方法,使其可供所有函數存取。
getDetails.call(details, 'Tamil Nadu', 'India'); // Manoj from Chennai, Tamil Nadu, India // Polyfill Function.prototype.myCall = function (ref, ...args) { if (typeof Function.prototype.call === 'function') { // Checks whether the browser supports call method return this.call(ref, ...args); } else { ref = ref || globalThis; let funcName = Math.random(); // Random is used to overwriting a function name while (ref.funcName) { funcName = Math.random(); } ref[funcName] = this; let result = ref[funcName](...args); delete ref[funcName]; return result; } } getDetails.myCall(details, 'Tamil Nadu', 'India'); // Manoj from Chennai, Tamil Nadu, India
2。申請方式:
讓我們為apply() 建立一個polyfill。我們將向 Function.prototype 新增自訂 apply 方法,使其可供所有函數存取。
getDetails.apply(details, ['Tamil Nadu', 'India']); // Manoj from Chennai, Tamil Nadu, India // Polyfill Function.prototype.myApply = function (ref, args) { if (typeof Function.prototype.apply === 'function') { // Checks whether the browser supports call method this.apply(ref, args); } else { ref = ref || globalThis; let funcName = Math.random(); // Random is to avoid duplication while (ref.funcName) { funcName = Math.random(); } ref[funcName] = this; let result = ref[funcName](args); delete ref[funcName]; return result; } } getDetails.myApply(details, 'Tamil Nadu', 'India'); // Manoj from Chennai, Tamil Nadu, India
3。綁定方法
讓我們為bind() 建立一個polyfill。我們將向 Function.prototype 新增自訂 bind 方法,使其可供所有函數存取。
let getFullDetails = getDetails.bind(details, 'Tamil Nadu'); getFullDetails(); // Manoj from Chennai, Tamil Nadu getFullDetails('India'); // Manoj from Chennai, Tamil Nadu, India // Polyfill Function.prototype.myBind = function (ref, ...args) { if (typeof Function.prototype.bind === 'function') { return this.bind(ref, ...args); } else { let fn = this; return function (...args2) { return fn.apply(ref, [...args, ...args2]); // Merge and apply arguments } } } let getFullDetails = getDetails.myBind(details, 'Tamil Nadu'); // Manoj from Chennai, Tamil Nadu getFullDetails('India'); // Manoj from Chennai, Tamil Nadu, India
感謝您的閱讀!我希望您覺得這個部落格內容豐富且引人入勝。如果您發現任何不準確之處或有任何回饋,請隨時告訴我。
以上是寫 polyfill — Javascript的詳細內容。更多資訊請關注PHP中文網其他相關文章!