手写call
js
// 手写call,将调用myCall的函数传递给context
Function.prototype.myCall = function(context,...args) {
context = context ?? globalThis;
const a = Symbol();
context[a] = this;
const result = context[a](...args);
delete context[a];
return result;
}
const obj = {name : 'Tom'};
function greet(age,city) {
console.log(`${this.name},${age},${city}`);
}
greet.myCall(obj,18,'USa');
手写apply
js
// 逻辑和call一样,就是接受的是参数数组
Function.prototype.myApply = function(context,argArray) {
context = context ?? globalThis;
const a =Symbol();
context[a] = this;
let result;
if(Array.isArray(argArray)) {
result = context[a](...argArray);
}else {
result = context[a]();
}
delete context[a];
return result;
}
const obj = {name : 'Tom'};
function greet(age,city) {
console.log(`${this.name},${age},${city}`);
}
greet.myApply(obj,[18,'usa']);
手写bind
js
// 手写bind
Function.prototype.myBind = function(context,...args) {
context = context ?? globalThis;
const fn = this;
const bound = function(...rest) {
if(this instanceof bound) {
return new fn(...args,...rest);
}else {
return fn.call(context,...args,...rest);
}
}
// 保证:new bound() instanceof fn === true
bound.prototype = Object.create(fn.prototype);
return bound;
}
const person = {
name: 'itheima'
}
function func(numA, numB, numC, numD) {
console.log(this)
console.log(numA, numB, numC, numD)
return numA + numB + numC + numD
}
const bindFunc = func.myBind(person, 1, 2)
new bindFunc(3,4);
console.log(new bindFunc(5,6) instanceof func);