call apply和bind都可以改变this指向
1.1 call
第一个参数改变this指向,剩余参数接受一个参数列表
1.1.1 语法
function.call(thisArg, arg1, arg2, ...)
复制代码
1.1.2 实例
function add (val1,val2) {
return this.a+this.b+val1+val2
}
let obj={
a:1,
b:2
}
console.log(add.call(obj,3,4)) //10
复制代码
1.1.3 手写
Function.prototype.myCall = function (context, ...args) {
// 获取第一个参数(注意第一个参数为null或undefined时,this指向window),构建对象
context = context ? Object(context) : window;
// 将对应函数传入该对象中
context.fn = this;
// 获取参数并执行相应函数
let result = context.fn(...args);
// 消除副作用
delete context.fn;
// 返回结果
return result;
}
console.log(add.myCall(obj,3,4))
复制代码
2.1 apply
第一个参数改变this指向,剩余参数接受一个参数数组
2.1.1 语法
function.call(thisArg, [arg1, arg2])
复制代码
2.1.2 实例
function add (val1,val2) {
return this.a+this.b+val1+val2
}
let obj={
a:1,
b:2
}
console.log(add.apply(obj,[3,4])) //10
复制代码
2.1.3 手写
Function.prototype.myApply = function (context, arr) {
context = context ? Object(context) : window;
context.fn = this;
let result = arr ? context.fn(...arr) : context.fun();
delete context.fn;
return result;
}
console.log(add.myApply(obj, [3, 4])); // 10
复制代码
3.1 bind
第一个参数改变this指向,剩余参数接受一个参数列表 ,bind返回一个新函数,需要手动调用
3.1.1 语法
function.call(thisArg, arg1, arg2)
复制代码
3.1.2 实例
function add (val1,val2) {
return this.a+this.b+val1+val2
}
let obj={
a:1,
b:2
}
console.log(add.bind(obj,3,4)()) //10
复制代码
3.1.3 手写
Function.prototype.myBind = function(context, ...args1) {
context = context ? Object(context) : window;
let _this = this
return function(...args2) {
context.fn = _this
let result = context.fn(...[...args1, ...args2])
delete context.fn
return result
}
}
console.log(add.myBind(obj, 3,4)()); // 10
复制代码
如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END