JavaScript 系列之 this(二)

199 阅读3分钟

这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战

二、改变 this 的指向

var name = "windowsName";
var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },

  func2: function () {
    setTimeout(function () {
      this.func1();
    }, 100);
  },
};
a.func2(); // this.func1 is not a function

在不使用箭头函数的情况下,是会报错的,因为最后调用 setTimeout 的对象是 window,但是在 window 中并没有 func1 函数。

2.1 使用 ES6 的箭头函数

箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined。

var name = "windowsName";
var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },

  func2: function () {
    setTimeout(() => {
      this.func1();
    }, 100);
  },
};
a.func2(); // Cherry

2.2 在函数内部使用 _this = this

如果不使用 ES6,那么这种方式应该是最简单的不会出错的方式了,我们是先将调用这个函数的对象保存在变量 _this 中,然后在函数中使用这个 _this,这样 _this 就不会改变了。

var name = "windowsName";
var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },

  func2: function () {
    var _this = this;
    setTimeout(function () {
      _this.func1();
    }, 100);
  },
};
a.func2(); // Cherry

这个例子中,在 func2 中,首先设置 var _this = this;,这里的 this 是调用 func2 的对象 a,为了防止在 func2 中的 setTimeout 被 window 调用而导致的在 setTimeout 中的 this 为 window。我们将 this(指向变量 a) 赋值给一个变量 _this,这样,在 func2 中我们使用 _this 就是指向对象 a 了。

2.3 使用 call、apply、bind

1、使用 call

var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },

  func2: function () {
    setTimeout(
      function () {
        this.func1();
      }.call(a),
      100
    );
  },
};
a.func2(); // Cherry

2、使用 apply

var a = {
  name: "Cherry",
  
  func1: function () {
    console.log(this.name);
  },
  
  func2: function () {
    setTimeout(
      function () {
        this.func1();
      }.apply(a),
      100
    );
  },
};
a.func2(); // Cherry

3、使用 bind

var a = {
  name: "Cherry",

  func1: function () {
    console.log(this.name);
  },
  
  func2: function () {
    setTimeout(
      function () {
        this.func1();
      }.bind(a)(),
      100
    );
  },
};
a.func2(); // Cherry

2.4 new 实例化一个对象

三、对 call 和 apply 和 bind 分析

3.1 call 和 apply 的区别

call 和 apply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同。

除了第一个参数外,call 可以接收一个参数列表,apply 只接受一个参数数组。

在 fun 函数运行时指定的 this 值:

  • fun.call(thisArg, arg1, arg2, ...)
  • func.apply(thisArg, [argsArray])
var a = {
  value: 1,
};
function getValue(name, age) {
  console.log(name);
  console.log(age);
  console.log(this.value);
}
getValue.call(a, "yck", "24"); // yck 24 1
getValue.apply(a, ["yck", "24"]); // yck 24 1

3.2 bind

bind() 方法创建一个新的函数, 当被调用时,将其 this 关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。

var a = {
  name: "Cherry",
  fn: function (a, b) {
    console.log(a + b);
  },
};
var b = a.fn;
b.bind(a, 1, 2)(); // 3

相关文章