回顾以前学习内容,并记录如下
手写call、apply、bind
Function.prototype.myCall = function (context) {
if (typeof this !== 'function') return;
const ctx = context ?? window;
ctx.fn = this;
const arr = [...arguments].slice(1);
const result = ctx.fn(...arr);
delete ctx.fn;
return result;
}
Function.prototype.myApply = function (context) {
if (typeof this !== 'function') return;
let ctx = context ?? window;
let arr = arguments[1];
ctx.fn = this;
let result = ctx.fn(arr);
delete ctx.fn;
return result;
}
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') return;
const ctx = context ?? window;
ctx.fn = this;
const arr = [...arguments].slice(1);
return function () {
ctx.fn(...arr)
}
}
Array.prototype.myforEach = function (callback) {
if (!Array.isArray(this)) throw 'this not a array';
let list = this;
for (let i = 0; i < list.length; i++) {
callback(list[i]);
}
}