// 官方写法,第二个参数类型必须为数组
foo.apply('obj', [0]); //实现该方法
// js实现
// 在函数参数中 argArray=[] 默认值
Function.prototype.hyApply = function(thisArg, argArray = []) {
// thisArg 必须是Object 类型, 由于arrArray传入时是个数组,所以给个默认值是[]
// 1.获取到真实需要调用的函数:获取当前this指向
var fn = this;
// 2.绑定this,不存在 指向 window
//@param thisArg — An object to which the this keyword can refer inside the new function.
// 在apply(),call(),bind()中this绑定值如果是 null 或 undefined 时 ,this 指向 window,
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
// 赋值
thisArg.fn = fn;
// 3.保存结果,输出结果
var result = thisArg.fn(...argArray);
// 4.删除fn属性
delete thisArg.fn
return result
};
function foo(num1, num2) {
console.log(this)
return num1 + num2
}
var result = foo.hyApply('obj', [1, 2, 3]) // 隐式调用 this 指向 foo
console.log(result)
var result3 = foo.apply('obj', [1, 2, 3])
console.log(result3);
//输出结果值
// {[String: 'obj'] fn: [Function: foo]}
// 3
// [String: 'obj']
// 3
js 实现 apply()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 1, 首先call()、apply()、bind() 都是用来重定义 this 这个对象的 例子1: <!DOCT...
- 1 call和apply是怎样使用的?call函数接收多个参数,第一个参数是this的指向,之后的参数都是函数的参...
- 之前写过两篇《面试官问:能否模拟实现JS的new操作符》和《面试官问:能否模拟实现JS的bind方法》 其中模拟b...