这是我参与8月更文挑战的第30天,活动详情查看:8月更文挑战
前言
“八月的色彩是用金子铸就的,明亮而珍贵;八月的色彩是用阳光酿造的,芬芳而灿烂。”
未来的日子,愿你把自己调至最佳状态,缓缓努力,慢慢变好 Y(^o^)Y
为什么会有
首先先看下以下例子:
var name = 'tom';
var age = 16;
var obj = {
name: 'jarry',
obj_age: this.age,
func: function() {
console.log('name: ', this.name, '; age: ', this.age);
}
}
console.log(obj.obj_age); // 16
// 注意这次的 this 指向
obj.func(); // name: jarry ; age: undefined
var job = '编码';
function jobs() {
console.log(this.job);
}
jobs(); // 编码
比较一下这两者 this 的差别,第一个打印里面的 this 指向 obj,第二个全局声明的 jobs() 函数 this 是 window。
作用和差异
call()、apply()、bind() 都是用来重定义 this 这个对象的!
var obj1 = {
name: '小明',
age: 18,
}
obj.func.call(obj1); // name: 小明 ; age: 18
obj.func.apply(obj1); // name: 小明 ; age: 18
<!-- 注意bind 后的返回值是一个函数 -->
obj.func.bind(obj1);
<!--
ƒ () {
console.log('name: ', this.name, '; age: ', this.age);
}
-->
obj.func.bind(obj1)(); // name: 小明 ; age: 18
apply 和 call 都是为了改变某个函数运行时的上下文而存在的(就是为了改变函数内部this的指向)
apply和call的调用返回函数执行结果。
bind 不会立即调用,而是返回一个新函数,称为绑定函数,其内的this指向为创建它时传入 bind 的第一个参数,你必须调用它才会被执行
call 、bind 、 apply 传参情况
var obj = {
name: 'jarry',
obj_age: this.age,
func: function(job, from) {
console.log('name: ', this.name, '; age: ', this.age, 'job: ', job, 'from: ', from);
}
}
var test = {
name: '小花',
age: 12
}
obj.func.call(test, '画画', '中国'); // name: 小花 ; age: 12 job: 画画 from: 中国
obj.func.apply(test, ['画画', '中国']); // name: 小花 ; age: 12 job: 画画 from: 中国
obj.func.bind(test, '画画', '中国')(); // name: 小花 ; age: 12 job: 画画 from: 中国
call 和 bind 都是直接传入对应的参数,使用逗号分隔开
apply 必须把参数放进一个数组中。
call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组
总结
call()
function.call(thisArg, arg1, arg2, ...)
thisArg 可选的。在 function 函数运行时使用的 this 值
apply()
func.apply(thisArg, [argsArray])
thisArg 调用绑定函数时作为 this 参数传递给目标函数的值
bind()
func.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg 调用绑定函数时作为 this 参数传递给目标函数的值
如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。
文章如有错误之处,希望在评论区指正🙏🙏。