/**
* 记录当前函数,返回一个新函数
* 1、通过new 调用新函数:如果原始函数返回的是一个对象,则返回该对象,否则返回构造函数为原始函数的新对象
* 2、将剩余参数和执行新函数的参数合并,使用指定的this去执行新函数,返回值由原始函数决定
* @param {*} ctx
* @param {...any} args
* @returns
*/
Function.prototype.myBind = function (ctx, ...args) {
const Fn = this;
return function (...rest) {
if (new.target) {
return new Fn(...args, ...rest);
} else {
return Fn.apply(ctx, [...args, ...rest]);
}
};
};
/**
* call改变this指向为第一个参数对象,然后该对象使用剩余参数执行函数,并返回结果
* @param {this指向} ctx
* @param {...any} args
* @returns
*/
Function.prototype.myCall = function (ctx, ...args) {
//globalThis 浏览器环境指向window,node环境指向global
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
const key = Symbol();
Object.defineProperty(ctx, key, {
value: this,
enumerable: false,
});
const result = ctx[key](...args);
delete ctx[key];
return result;
};
/**
* apply方法和call方法类似,不过apply方法只传两个参数,第二个参数会以数组形式传递
* @param {} ctx
* @param {*} argsArr
* @returns
*/
Function.prototype.myApply = function (ctx, argsArr) {
if (!argsArr) {
argsArr = [];
}
if (argsArr && typeof argsArr === "object") {
argsArr = Array.from(argsArr);
} else {
throw TypeError("CreateListFromArrayLike called on non-object");
}
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx);
const fn = this;
const key = Symbol();
Object.defineProperty(ctx, key, {
value: fn,
enumerable: false,
});
const result = ctx[key]();
delete ctx[key];
return result;
};
手写函数常用方法bind、call、apply
于 2024-12-28 19:15:33 首次发布
232

被折叠的 条评论
为什么被折叠?



