直接上代码
Array.prototype.myForEach = function (fn, self) {
if (typeof fn !== 'function') {
throw new TypeError(fn + 'is not a function')
}
for (let i = 0; i < this.length; i++) {
console.log(self)
fn.call(self, this[i], i, this)
}
}
let arr = [1,2,3]
arr.myForEach(function (value, index, array) {
console.log(value)
console.log(this)
}, arr)
代码很简单,写的时候发现一个点。就是里面函数如果是箭头函数,那么this执行就是{}
let arr = [1,2,3]
arr.forEach( (value, index, array) => {
console.log(this) // {}
}, arr)
原生forEach就有这个情况,所以后续如果需要使用this要注意不用箭头函数。