您现在的位置是:首页 > 编程语言学习 > 后端编程语言 > 文章正文 后端编程语言

javascript改变this指向的方法汇总

2022-09-16 10:02:42 后端编程语言

简介一、this指向this随处可见,一般谁调用,this就指向谁。this在不同环境下,不同作用下,表现的也不同。以下几种情况,this都是指向window1...

一、this指向

this随处可见,一般谁调用,this就指向谁。this在不同环境下,不同作用下,表现的也不同。

以下几种情况,this都是指向window

1、全局作用下,this指向的是window

  1. console.log(window); 
  2. console.log(this); 
  3. console.log(window == this); // true 

2、函数独立调用时,函数内部的this也指向window

  1. function fun() { 
  2.    console.log('我是函数体'); 
  3.    console.log(this);  // Window  
  4. fun(); 

3、被嵌套的函数独立调用时,this默认指向了window

  1. function fun1() { 
  2. function fun2() { 
  3. console.log('我是嵌套函数'); 
  4. console.log(this);  // Window 
  5. fun2(); 
  6. fun1(); 

4、自调执行函数(立即执行)中内部的this也是指向window

  1. (function() { 
  2. console.log('立即执行'); 
  3. console.log(this);   // Window 
  4. })() 

需要额外注意的是:

构造函数中的this,用于给类定义成员(属性和方法)箭头函数中没有this指向,如果在箭头函数中有,则会向上一层函数中查找this,直到window

二、改变this指向

1、call() 方法

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

(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;(2)第二个参数开始:将原函数的参数往后顺延一位

用法: 函数名.call()

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

2、apply() 方法

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

(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;(2)第二个参数开始:将原函数的参数放在一个数组中

用法: 函数名.apply()

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

3、bind() 方法

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

用法: 函数名.bind()

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

 

站点信息