手写实现call方法和apply方法
通过查MDN文档我们可以发现,call和apply只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。 这里是手动实现代码
function person(a, b, c, d) { return { name: this.name, a: a, b: b, c: c, d: d } } const egg = { name: 小蛋, } Function.prototype.newCall = function(obj, ...arguments) { // 给默认值window const object = obj || window object.p = this const argumentsList = [] for (let i = 0; i < arguments.length; i++) { argumentsList.push(arguments[i]) } const result = object.p(...argumentsList) delete object.p return result } Function.prototype.newApply = function(obj, arr) { const object = obj || window object.p = this if(!arr) { return obj.p() } else { const argumentsList = [] for (let i = 0; i < arr.length; i++) { argumentsList.push(arr[i]) } const result = object.p(...argumentsList) delete object.p return result } }