JS中怎么改变this的指向

树叶云

1、call() 方法

call() 方法的个参数必须是指定的对象,然后方法的原参数,挨个放在后面。

(1)个参数:传入该函数this执行的对象,传入什么强制指向什么;

(2)第二个参数开始:将原函数的参数往后顺延一位

用法: 函数名.call()

function fun() {
    console.log(this);  // 原来的函数this指向的是 Window
}
fun();
 
function fun(a, b) {
    console.log(this); // this指向了输入的 字符串call
    console.log(a + b);
}
//使用call() 方法改变this指向,此时个参数是 字符串call,那么就会指向字符串call
fun.call('call', 2, 3)  // 后面的参数就是原来函数自带的实参

2、apply() 方法

apply() 方法的个参数是指定的对象,方法的原参数,统一放在第二个数组参数中。

(1)个参数:传入该函数this执行的对象,传入什么强制指向什么;

(2)第二个参数开始:将原函数的参数放在一个数组中

用法: 函数名.apply()

function fun() {
    console.log(this);  // 原来的函数this指向的是 Window
}
fun();
 
function fun(a, b) {
    console.log(this); // this指向了输入的 字符串apply
    console.log(a + b);
}
//使用apply() 方法改变this指向,此时个参数是 字符串apply,那么就会指向字符串apply
fun.apply('apply', [2, 3])  // 原函数的参数要以数组的形式呈现

3、bind() 方法

bind() 方法的用法和call()一样,直接运行方法,需要注意的是:bind返回新的方法,需要重新 调用 是需要自己手动调用的

用法: 函数名.bind()

function fun() {
    console.log(this);  // 原来的函数this指向的是 Window
}
fun();
 
function fun(a, b) {
    console.log(this); // this指向了输入的 字符串bind
    console.log(a + b);
}
//使用bind() 方法改变this指向,此时个参数是 字符串bind,那么就会指向字符串bind
let c = fun.bind('bind', 2, 3);
c(); // 返回新的方法,需要重新调用
// 也可以使用下面两种方法进行调用
// fun.bind('bind', 2, 3)();
// fun.bind('bind')(2, 3);

 

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/114911.html<

(0)
运维的头像运维
上一篇2025-02-17 23:26
下一篇 2025-02-17 23:28

相关推荐

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注