JS:对“this”的学习

JS:对“this”的学习。

前言

更多笔记,请参看IT老兵驿站

有半个多月没有更新博客了,这半个多月一直在加班,实在没有精力更新,现在到了调整期,可以将前一段时间的工作进行一下整理。

之前对JS的this的理解一直有点模糊,这次总结一下,因为在工作中总遇到this的问题,如果一直这么模模糊糊,将会在以后的工作中带来麻烦,而对于这种躲不开的麻烦,早解决肯定要比晚解决好。

这篇帖子是针对参考中的w3schools的一篇帖子进行学习、翻译和理解,但我感觉w3schools这篇帖子层次有点不是太清楚。

正文

this是什么

例子:

1
2
3
4
5
6
7
8
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

这里的this指代的是什么呢?

What is “this”?
In a function definition, this refers to the “owner” of the function.
In the example above, this refers to the person object.
The person object “owns” the fullName method.

在函数定义中,this指代函数的“拥有者”,例如上面例子中,this就代表person这个对象。

默认绑定

Default Binding
When used alone, this refers to the Global object.
In a browser the Global object is [object Window]:

默认的绑定,单独使用时,this就指代全局对象。个人理解,这一条和上一条不矛盾,this还是指代拥有这个变量或者函数的对象,这个时候是全局变量拥有这个变量,所以就指向了全局变量。

In strict mode, this will be undefined, because strict mode does not allow default binding:

但是在严格模式下,this将会是undefined,因为严格模式不允许默认绑定。

明确绑定

Explicit Function Binding
The call() and apply() methods are predefined JavaScript methods.
They can both be used to call an object method with another object as argument.

明确的函数绑定,call()和apply()是JS预定义的方法,他们可以被用于使用另外一个对象作为参数,调用这个对象的方法。

1
2
3
4
5
6
7
8
9
10
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"John",
lastName: "Doe",
}
person1.fullName.call(person2); // Will return "John Doe"

看上面这个例子,this指向了person2,最终输出的是person2的属性。

总结

这样一梳理,感觉对于this的理解就清晰了。

参考

https://www.w3schools.com/js/js_this.asp