什么是this?

在JS中,this其实是多余的,它的作用是让JS看起来像JAVA,this我理解为当前的执行环境。

全局中的this

全局中的this一般指向全局对象,浏览器中的全局对象就是 window。如:

  1. console.log(this.document === document); //true
  2. console.log(this === window); //true
  3. this.a = 1234;
  4. console.log(window.a); //1234

普通函数的 this

一般函数的 this也是指向 window,在 nodeJS 中为 global object。如:

  1. function fn () {
  2. return this;
  3. }
  4. console.log(fn() === window);//true, global object

需要注意的是在严格模式中,函数的 this 为 undefined,因为严格模式禁止this关键字指向全局对象:

  1. function a1 () {
  2. "use strict";//使用严格模式
  3. return this;
  4. }
  5. console.log(a1() === undefined);//true

对象方法的函数的 this

  1. var o = {
  2. age: 18,
  3. f: function() {
  4. return this.age;
  5. }
  6. };
  7. console.log(o.f()); // 18

f 为对象 o 的方法。这个方法的 this 指向这个对象,在这里即对象 o。

普通函数调用

函数也可以直接被调用,此时 this 绑定到全局对象。在浏览器中,window 就是该全局对象。

  1. window.name = 'globalName';
  2. var getName = function(){
  3. return this.name
  4. };
  5. console.log(getName());//globalName

对象原型链上的this

  1. var o = {
  2. f: function() {
  3. return this.a + this.b;
  4. }
  5. };
  6. var p = Object.create(o);
  7. p.a = 1;
  8. p.b = 2;
  9. console.log(p.f()); //3

通过 var p = Object.create(o) 创建的对象,p 是基于原型 o 创建出的对象。
p 的原型是 o,调用 f() 的时候是调用了 o 上的方法 f(),这里面的 this 是可以指向当前对象的,即对象 p。

构造器中的 this

  1. function MyClass() {
  2. this.a = 25;
  3. }
  4. var o = new MyClass();
  5. console.log(o.a); //25

new MyClass() 的时候,MyClass()中的 this 会指向一个空对象,这个对象的原型会指向 MyClass.prototype。MyClass()没有返回值或者返回为基本类型时,默认将 this 返回。

  1. function a2() {
  2. this.a = 18;
  3. return {
  4. a: 28
  5. };
  6. }
  7. o = new a2();
  8. console.log(o.a); //28

因为返回了对象,将这个对象作为返回值。

call/apply 方法与 this

在call/apply 方法中,this永远指向它的第一个参数。如:

  1. function add(c, d) {
  2. return this.a + this.b + c + d;
  3. }
  4. var o = {
  5. a: 1,
  6. b: 3
  7. };
  8. add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
  9. add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

在遇到this产生困惑的时候,建议先将其改写成call/apply的形式,更方便判断。