JS 中改变函数的this指向,call,apply,bind方法的使用和区别

JS 中改变函数的this指向,call,apply,bind方法的使用和区别

1. 普通函数调用,此时 this 指向 window

function a() {
       console.log(this);   // window
}
a();

2.构造函数调用, 此时 this 指向 实例对象

function Person(age, name) {
         this.age = age;
         this.name = name
         console.log(this)  // 此处 this 分别指向 Person 的实例对象 p1 p2
}
var p1 = new Person(18, 'zs')
var p2 = new Person(18, 'ww')

3.对象方法调用, 此时 this 指向 该方法所属的对象

var obj = {
       fn: function () {
         console.log(this); // obj
       }
     }
    obj.fn();

4. call()方法 文档说明

  1. function.call(thisArg, arg1, arg2, …)
  2. thisArg 是想要将this指向的那个对象或者方法
  3. arg1,arg2…传递的参数
    使用call之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
const obj = {
    name: "小火车"
}
function fn(a , b) {
    console.log(this) // obj
    console.log(a + b) // 4
}
fn.call(obj,2,2)

5.apply()方法 文档说明

  1. func.apply(thisArg, [argsArray])
  2. thisArg 是想要将this指向的那个对象或者方法
  3. argsArray 一个数组或者类数组对象
    使用apply之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
const obj = {
    name: "小火车"
}
function fn(a,b) {
    console.log(this) // obj
    console.log(a + b) // 4
}
fn.apply(obj,[2,2])

6. bind()方法 文档说明

  1. function.bind(thisArg[, arg1[, arg2[, …]]])
  2. thisArg 是想要将this指向的那个对象或者方法
  3. arg1,arg2…传递的参数
    使用bind之后,函数会立即执行,fn函数中的this指向被改变,指向了obj对象
const obj = {
    name: "小火车"
}
function fn(a,b) {
    console.log(this) // obj
    console.log(a + b) // 4
}
const getFn = fn.bind(obj,2,2)
getFn()

共同点
都可以改变this的指向
区别

  1. call和apply会立即调用函数,并且改变函数内部的this指向

  2. call和apply传递的参数不同,call参数的形式是arg1, arg2,
    …,apply参数的形式必须是[arg1,arg2,…]

  3. bind不会立即调用函数,可以改变函数内部的this指向

猜你喜欢

转载自blog.csdn.net/web2001chu/article/details/107958788