0%

js中的this

this 的指向

在 ES5 中,其实 this 的指向,始终坚持一个原理:this 永远指向最后调用它的那个对象。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
function foo() {
console.log(this.a)
}
var a = 1
foo()

const obj = {
a: 2,
foo: foo
}
obj.foo()

const c = new foo()

接下来我们一个个分析上面几个场景

  • 对于直接调用 foo 来说,不管 foo 函数被放在了什么地方,this 一定是 window
  • 对于 obj.foo() 来说,我们只需要记住,谁调用了函数,谁就是 this,所以在这个场景下 foo 函数中的 this 就是 obj 对象
  • 对于 new 的方式来说,this 被永远绑定在了 c 上面,不会被任何方式改变 this
    说完了以上几种情况,其实很多代码中的 this 应该就没什么问题了,下面让我们看看箭头函数中的 this
    1
    2
    3
    4
    5
    6
    7
    8
    function a() {
    return () => {
    return () => {
    console.log(this)
    }
    }
    }
    console.log(a()()())
    首先箭头函数其实是没有 this 的,箭头函数中的 this 只取决包裹箭头函数的第一个普通函数的 this。在这个例子中,因为包裹箭头函数的第一个普通函数是 a,所以此时的 this 是 window。

改变this指向

在函数内部使用 that = this

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var name = "windowsName";

var a = {

name : "Samonnite",

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

func2: function () {
var that = this;
setTimeout( function() {
that.func1()
},100);
}

};

a.func2() // Samonnite

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

使用 apply、call、bind

1
2
3
4
5
6
7
8
9
10
11
var name = 'Bob';
var person = {
name: 'Samonnite',
age: 24
}

function sayName() {
console.log(this.name);
}

sayName.call(person); // Samonnite

这里是使用了 call 方法来改变了 this的执行环境,至于使用 apply,效果一样,只是二者差别在于传入参数的不同。

1
2
func.call(context, arg1, arg2, ...)
func.apply(context, [arg1, arg2, ...])

以上就是 this 的规则了,但是可能会发生多个规则同时出现的情况,这时候不同的规则之间会根据优先级最高的来决定 this 最终指向哪里。

首先,new 的方式优先级最高,接下来是 bind 这些函数,然后是 obj.foo() 这种调用方式,最后是 foo 这种调用方式,同时,箭头函数的 this 一旦被绑定,就不会再被任何方式所改变。