实现 call 方法
功能
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
- 传入的
this如果是null、undefined时,会自动替换为指向全局对象,原始值会被转换了对应的包装对象
实现
Function.prototype.myCall = function (thisArg, ...args) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
thisArg.fn = fn;
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function foo() {
console.log(this);
}
function sum(num1, num2) {
console.log(this, num1, num2);
return num1 + num2;
}
var obj = {
name: "zhangsan",
age: 28,
};
foo.call(null);
foo.call(undefined);
foo.call(obj);
foo.call(100);
foo.myCall(null);
foo.myCall(undefined);
foo.myCall(obj);
foo.myCall(100);
var result1 = sum.call(obj, 10, 20);
console.log(result1);
var result2 = sum.myCall(obj, 10, 20);
console.log(result2);
实现 apply 方法
功能
apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数
- 传入的
this如果是null、undefined时,会自动替换为指向全局对象,原始值会被转换了对应的包装对象
实现
Function.prototype.myApply = function (thisArg, args) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
thisArg.fn = fn;
args = args || [];
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function foo() {
console.log(this);
}
function sum(num1, num2) {
console.log(this, num1, num2);
return num1 + num2;
}
var obj = {
name: "zhangsan",
age: 28,
};
foo.apply(null);
foo.apply(undefined);
foo.apply(obj);
foo.apply(100);
foo.myApply(null);
foo.myApply(undefined);
foo.myApply(obj);
foo.myApply(100);
var result1 = sum.apply(obj, [10, 20]);
console.log(result1);
var result2 = sum.myApply(obj, [10, 20]);
console.log(result2);
实现 bind 方法
功能
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
实现
Function.prototype.myBind = function (thisArg, ...args1) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
function bindedFn(...args2) {
thisArg.fn = fn;
var args = [...args1, ...args2];
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
}
return bindedFn;
};
function foo(...args) {
console.log(this, ...args);
}
var obj = {
name: "zhangasan",
age: 28,
};
var foo1 = foo.myBind(null);
foo1(10);
var foo2 = foo.myBind(obj, 10);
foo2(20);
- 如果认为本篇知识点梳理的尚可,欢迎点赞
- 如果有需要补充、指正的地方,也欢迎评论留言哦~