文章目录
- 如何解释Javascript中的this值?
-
- 1.函数调用
- 2.对象方法调用
- 3.构造函数调用
- [4.apply、call、bind 方法调用](#4.apply、call、bind 方法调用)
- 5.箭头函数中的this
如何解释Javascript中的this值?
在 JavaScript 中,this 的值是动态的,通常会由被使用的函数来决定。所以,影响 this 的值不是定义的时候,关键在于会在哪里被调用。
this 值 5 种判断方式
- 函数调用
- 物体方法调用
- 构造函数调用
- apply call bind 方法调用
- 箭头函数中的 this
1.函数调用
当一个函数不是属于一个对象中的方法时,直接作为函数来调用时,this 会指向全局对象,在浏览器中,默认为 Window。但有一点要注意的是,如果是在严格模式下,this 为 undefined。
例子如下,因为是一般函数调用,this 总是指向 Window,所以一个输出结果是 Window。而因为在全局范围中用 var 定义 name 变量。name 变量会绑定在 Window 对象上,第二个输出结果也就等同于 window.name 的值(如果是用 let 定义,并不会绑定在 Window 对象上)
javascript
var name = "John";
function callThis() {
console.log(this);
console.log(this.name);
}
callThis();
// Window
// John
2.对象方法调用
当一个函数是作为一个对象的方法来调用时,this 会指向这个对象
javascript
const john = {
name: "john",
callJohn() {
console.log(`hello, ${this.name}`);
},
};
john.callJohn(); // hello, john
|---------------------------------------------------------|
| this 的指向取决于函数被调用的方式,而不是函数定义的位置。 因为使用的时候是 join.xxx,对象调用。 |
关键反例:
javascript
const john = {
name: "john",
callJohn() {
console.log(this.name);
},
};
const fn = john.callJohn;
fn(); // undefined(或严格模式下报错)
3.构造函数调用
当一个函数使用 new 调用的时候,会出现如下情况

重点来看this 指针的调用
第一处 this 指针
- 构造函数执行时,this 指向新创建的 object,所以 this.brand = brand 实际是在给 object 添加属性。
第二处 this 指针
- 调用 newIPhone.getBrand() 时,因为是对象方法调用,this 自动指向 newIPhone,所以能正确返回该对象的 brand。
4.apply、call、bind 方法调用
我们也可以使用 apply、call、bind 方法来指定 this 指向的对象。
-
apply方法接受两个参数,第一個是 this 绑定的对象,第二个要放入要传入函数的数组参数,并执行这个函数。 -
call方法类似为apply,唯一不同的地方是,apply第二个参数是数组,但call则是参数逐个传。 -
bind方法传入一个对象和要传入的参数,不同于apply和call,bind不会立即执行,而是会返回新的函数。
举例如下:
javascript
function greet(greeting, punctuation) {
console.log(`${greeting}, I am ${this.name}${punctuation}`);
}
const person = {
name: "Alice",
};
apply ------ 立即执行,参数用数组传
javascript
greet.apply(person, ["Hi", "~"]);
//Hi, I am Alice~
call ------ 立即执行,参数逐个传
javascript
greet.call(person, "Hello", "!");
//Hi, I am Alice~
bind ------ 不立即执行,返回一个新函数
const boundGreet = greet.bind(person, "Hey");
此时:
- this 已经被固定为 person
- "Hey" 被提前绑定为第一个参数
- 函数还没执行
执行返回的新函数:
javascript
boundGreet("!!!");
// Hey, I am Alice!!!
补充知识点:
|---------------------------------------------------------------------|
| 为什么 bind 常用于事件 / 回调? setTimeout(greet.bind(person, "Hello"), 1000); |
|-----------------------------------------------|
| 因为:setTimeout 会丢失原来的 this bind 可以提前把 this 固定住 |
5.箭头函数中的this
ES6 中介紹了一种新的函数形式 - 箭头函数(arrow function)。但要注意的是,箭头函数并没有属于自己的 this 值,箭头函数的 this 会从他的外层函数继承,若他的外层函数也同为箭头函数 ,則回继续向上找,直到找到全局环境的预设 this 值(例如:浏览器中就是 window)。
let getThis = () => this;
console.log(getThis() === window); // true