提供某些浏览器或环境本身不支持的功能的代码。简单来说,就是浏览器后备。
在为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中文网其他相关文章!