方法说明javascript
apply方法的做用和call方法同样,不一样之处在于提供参数的方式,apply使用参数数组,而call使用一组参数列表
源码关键点在于java
同Function.prototype.call方法的实现一致,仍是要在传递进来的上下文对象中构建一个须要执行的方法
源码数组
Function.prototype.myApply = function (ctx, args) { ctx = ctx || window const fn = Symbol() ctx[fn] = this const res = ctx[fn](...args) delete ctx[fn] return res } // 示例代码 function test (arg1, arg2) { return `${this.name}, ${arg1} ${arg2}` } const obj = { name: 'I am obj' } const res = test.myApply(obj, ['hello', 'world !!']) console.log(res) // I am obj, hello world !!