
一段代码,提供某些浏览器或环境本身不支持的功能。简单来说,就是浏览器后备。
在为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// polyfillfunction.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 方法,以使其可供所有函数访问。
一览妙笔
自媒体、编剧、营销人员写作工具
26 查看详情
getdetails.apply(details, ['tamil nadu', 'india']); // manoj from chennai, tamil nadu, india// polyfillfunction.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。绑定方法
立即学习“Java免费学习笔记(深入)”;
让我们为bind() 创建一个polyfill。我们将向 function.prototype 添加自定义 bind 方法,以使其可供所有函数访问。
let getFullDetails = getDetails.bind(details, 'Tamil Nadu');getFullDetails(); // Manoj from Chennai, Tamil NadugetFullDetails('India'); // Manoj from Chennai, Tamil Nadu, India// PolyfillFunction.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 NadugetFullDetails('India'); // Manoj from Chennai, Tamil Nadu, India
感谢您的阅读!我希望您发现这个博客信息丰富且引人入胜。如果您发现任何不准确之处或有任何反馈,请随时告诉我。
以上就是编写 polyfill — Javascript的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/895141.html
微信扫一扫
支付宝扫一扫