Skip to content

ES6 中的 this

this指向

普通函数的 this

谁调用了函数或者方法,那么这个函数或者对象中的this就指向谁

js
let getThis = function () {
  console.log(this);
};

let obj = {
  name: "Jack",
  getThis: function () {
    console.log(this);
  },
};
//getThis()方法是由window在全局作用域中调用的,所以this指向调用该方法的对象,即window
getThis(); //window
//此处的getThis()方法是obj这个对象调用的,所以this指向obj
obj.getThis(); //obj

匿名函数的 this

匿名函数的执行具有全局性,则匿名函数中的this指向是window,而不是调用该匿名函数的对象;

js
let obj = {
  getThis: function () {
    return function () {
      console.log(this);
    };
  },
};
obj.getThis()(); //window

//提前保存this,使this指向调用该方法的对象
let obj = {
  getThis: function () {
    //提前保存this指向
    let _this = this;
    return function () {
      console.log(_this);
    };
  },
};
obj.getThis()(); //obj

箭头函数的 this

  1. 箭头函数中的this是在函数定义的时候就确定下来的,而不是在函数调用的时候确定的;
  2. 箭头函数中的this指向父级作用域的执行上下文;
  3. 箭头函数无法使用 applycallbind方法改变this指向,因为其this值在函数定义的时候就被确定下来

技巧

因为 javascript 中除了全局作用域,其他作用域都是由函数创建出来的,所以如果想确定this的指向,则找到离箭头函数最近的function,与该function平级的执行上下文中的this即是箭头函数中的this

js
//例1:距离箭头函数最近的是getThis(){},与该函数平级的执行上下文是obj中的执行上下文
let obj = {
  //此处的this即是箭头函数中的this
  getThis: function () {
    return () => {
      console.log(this);
    };
  },
};
obj.getThis()(); //obj

//例2:代码中有两个箭头函数,由于找不到对应的function,所以this会指向window对象。
let obj = {
  getThis: () => {
    return () => {
      console.log(this);
    };
  },
};
obj.getThis()(); //window

this 绑定

可以使用callapplybind方法显式地绑定this

三者区别:

  1. callapply会调用函数,并且改变函数内部this指向。
  2. callapply传递的参数不一样,call传递参数 arg1,arg2...形式 apply必须数组形式。
  3. bind不会调用函数,可以改变函数内部this指向。

主要应用场景:

  1. call 经常做继承。
  2. apply 经常跟数组有关系,比如借助于数学对象实现数组最大值最小值。
  3. bind 不调用函数,但是还想改变this指向,比如改变定时器内部的this指向。

call

call()方法调用一个对象。简单理解为调用函数的方式,但是它可以改变函数的this指向。

js
//call 的主要作用也可以实现继承
function Person(uname, age) {
  this.uname = uname;
  this.age = age;
}
function Son(uname, age) {
  // 使用 call 方法调用 Person 构造函数,并将 this 绑定到 Son 的实例
  // 这样,Person 构造函数中的 this.uname 和 this.age 就会被赋值到 Son 的实例上
  Person.call(this, uname, age);
}
var son = new Son("zhang", 12);
console.log(son); // 输出: Son { uname: 'zhang', age: 12 }

apply

apply()方法调用一个函数。简单理解为调用函数的方式,但是它可以改变函数的 this指向,但它接受一个参数数组,而不是一组参数

js
function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

const person = { name: "Alice" };

greet.apply(person, ["Hello", "!"]); // 输出: Hello, Alice!

bind

bind方法创建一个新的函数,并将this绑定到指定的对象。这个新函数可以在稍后调用,并且可以接受参数。

js
function greet(greeting) {
  console.log(greeting + ", " + this.name);
}

const person = { name: "Alice" };

const boundGreet = greet.bind(person);
boundGreet("Hello"); // 输出: Hello, Alice

如有转载或 CV 的请标注本站原文地址