文章博客

技术团队文档示例


【工具函数】apply

<h5>模拟apply的功能</h5> <hr /> <p>改变this的指向</p> <pre><code class="language-javascript">/** * @description myApply 模拟apply * @param {object} obj 对象 * 给对象中添加方法然后,删除这个对象中的方法 */ Function.prototype.myApply = function(obj){ var obj = obj || window; obj.fn = this; var args = arguments[1]; var result; if(args){ result = obj.fn(...args) }else{ result = obj.fn() } delete obj.fn return result } let a = { value: 1 } function getValue(name, age) { console.log(name) console.log(age) console.log(this.value) } getValue.myApply(a, ['yck', '24']) //两者执行效果一样 getValue.myApply(a, ['yck', '24']) console.log(a)</code></pre> <p>参考链接:<a href="https://yuchengkai.cn/docs/frontend/#%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0-call-%E5%92%8C-apply">https://yuchengkai.cn/docs/frontend/#%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0-call-%E5%92%8C-apply</a></p>

页面列表

ITEM_HTML