获得徽章 16
- #每日一题# 实现JS中bind方法
Function.prototype.bind = function (thisArg, ...arg) {
if (typeof this !== 'function') {
throw new Error("Function.prototype.bind must be a function")
}
if (thisArg === null || thisArg === undefined) {
thisArg = window;
} else {
thisArg = Object(thisArg);
}
const func = this;
const bound = function (...boundArgsArray) {
let isNew = false;
try {
isNew = this instanceof func;
} catch (e) {}
return func.apply(isNew ? this : thisArg, arg.concat(boundArgsArray));
}
const Empty = function () { };
Empty.prototype = this.prototype;
bound.prototype = new Empty();
return bound;
}展开评论点赞 - #每日一题# 实现JS中apply方法
Function.prototype.apply = function(thisArgs,args){
if(typeof this !== "function"){
throw new Error('Function.prototype.apply must be a function!')
}
if(thisArgs === null || thisArgs === undefined){
thisArgs = window;
}else{
thisArgs = Object(thisArgs)
}
const func = Symbol("func");
thisArgs[sync] = this;
let result;
if(typeof args === 'object' && length in args){
result = thisArgs[func](...Array.from(args))
}else if(argsArray === undefined || argsArray === null){
result = thisArgs[func](args)
}else{
throw new Error("CreateListFromArrayLike called on non-object")
}
delete thisArgs[sync];
return result;
}展开评论点赞 - #每日一题# 实现JS中call方法
Function.prototype.call = function (thisArg, ...argsArray) {
if (typeof this !== 'function') {
throw new TypeError(
"Function.prototype.call was called on which is not a function"
);
}
if (thisArg === undefined || thisArg === null) {
thisArg = window;
} else {
thisArg = Object(thisArg)
}
const func = Symbol("func");
thisArg[func] = this;
let result;
if (argsArray.length) {
result = thisArg[func](...argsArray);
} else {
result = thisArg[func]();
}
delete thisArg[func];
return result;
}展开评论点赞