方法說明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 !!