上一篇分享了【不同函数的this默认取值】,那么如何动态指定函数 this 值呢?今天给大家分享改变this指向的三种方法:
1.call
使用 call
方法调用函数,同时指定函数中 this
的值,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this);
}
let user = {
name: '小明',
age: 18
}
let student = {
name: '小红',
age: 16
}
// 调用函数并指定 this 的值
sayHi.call(user); // this 值为 user
sayHi.call(student); // this 值为 student
// 求和函数
function counter(x, y) {
return x + y;
}
// 调用 counter 函数,并传入参数
let result = counter.call(null, 5, 10);
console.log(result); //15
</script>
总结:
call
方法能够在调用函数的同时指定 this
的值- 使用
call
方法调用函数时,第1个参数为 this
指定的值 call
方法的其余参数会依次自动传入函数做为函数的参数
2.apply
使用 apply 方法调用函数,同时指定函数中 this
的值,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this)
}
let user = {
name: '小明',
age: 18
}
let student = {
name: '小红',
age: 16
}
// 调用函数并指定 this 的值
sayHi.apply(user) // this 值为 user
sayHi.apply(student) // this 值为 student
// 求和函数
function counter(x, y) {
return x + y
}
// 调用 counter 函数,并传入参数
let result = counter.apply(null, [5, 10])
console.log(result) //15
</script>
总结:
apply
方法能够在调用函数的同时指定 this
的值- 使用
apply
方法调用函数时,第1个参数为 this
指定的值 apply
方法第2个参数为数组,数组的单元值依次自动传入函数做为函数的参数
3.bind
bind
方法并不会调用函数,而是创建一个指定了 this
值的新函数,使用方法如下代码所示:
<script>
// 普通函数
function sayHi() {
console.log(this)
}
let user = {
name: '小明',
age: 18
}
// 调用 bind 指定 this 的值
let sayHello = sayHi.bind(user);
// 调用使用 bind 创建的新函数
sayHello() //this指向user
</script>
注:bind
方法创建新的函数,与原函数的唯一的变化是改变了 this
的值。
后续会分享更多关于javaScript的知识,欢迎大家关注和评论~