JavaScript如何改变this指向?三种方法浅析

 2770

JavaScript如何改变this指向?下面本篇文章给大家介绍一下JS改变this指向的三种方法,希望对大家有所帮助!


JavaScript如何改变this指向?三种方法浅析


一、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. }
  5. fun();


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

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


2、apply() 方法

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

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

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

用法: 函数名.apply()

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


3、bind() 方法

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

调用

是需要自己手动调用的

用法: 函数名.bind()

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


本文网址:https://www.zztuku.com/index.php/detail-13102.html
站长图库 - JavaScript如何改变this指向?三种方法浅析
申明:本文转载于《博客园》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐