js 超详细的手写call、apply、bind
程序员文章站
2022-07-14 14:26:46
...
手写call
Function.prototype.myCall = function (context, ...arg) {
// 此时的 this 指向的是小数点前面的变量 也就是 obj.getName
// 并将 obj.getName 赋值给 context 的 fn 属性
// 使用 context.fn 执行的时候,this 指向小数点前面的对象 context
context.fn = this;
let result = context.fn(...arg);
return result;
}
let obj1 = {
name: "xiaohei",
age: 18,
getName: function () {
console.log(this.name);
}
}
let obj2 = {
name: "xiaobai"
}
obj1.getName.call(obj2); // 'xiaobai'
手写apply
+ 与 call
基本一致,就是穿的是数组,不再需要解构
Function.prototype.myApply = function (context, arg) {
// 此时的 this 指向的是小数点前面的变量 也就是 obj.getName
// 并将 obj.getName 赋值给 context 的 fn 属性
// 使用 context.fn 执行的时候,this 指向小数点前面的对象 context
context.fn = this;
let result = context.fn(arg);
return result;
}
let obj1 = {
name: "xiaohei",
age: 18,
getName: function () {
console.log(this.name);
}
}
let obj2 = {
name: "xiaobai"
}
obj1.getName.myApply(obj2); // 'xiaobai'
** 手写bind**
Function.prototype.myBind = function (context, ...arg) {
// 记录 调用 this 的主体 也就是 obj1.getName
let _this = this;
let fn = function () {
// context 要改成的 this 对象,也就是 obj2 , 参数可能会从两个地方传过来,进行参数合并
_this.apply(context, arg.concat(Array.prototype.slice.call(arg)));
}
// 保证返回的函数 原型链上的属性 不丢失
if (_this.prototype) {
fn.prototype = Object.create(this.prototype);
}
// 不会立即执行,返回 一个函数
return fn;
}
obj1.getName.myBind(obj2, 11)(22); // xiaobai Arguments(2) [11, 11...
下一篇: Mysql创建远程连接新用户