JavaScript中的this

在面向对象的语言中,this 都是指向当前对象的。而在 JavaScript 中 this 会随着执行环境的改变而改变。

  • 在对象方法中,this 表示该方法所属的对象。
  • 如果单独使用,this 表示全局对象。
  • 在函数中,this 表示全局对象。
  • 在函数中,在严格模式下,this 是未定义的(undefined)。
  • 类似 call() 、 apply() 、bind() 方法可以将 this 引用到任何对象。
  • 箭头函数中没有this
1
var person = {
2
  name:'张三',
3
  age:22,
4
  sayHi:function(){
5
    console.log(this)
6
    console.log(`你好,我是${this.name},今年${this.age}岁`)
7
  }
8
}

对象方法中的this,指向的是调用方法的对象
此时 console this,打印的是 person 对象

1
person.sayHi();

如果我们把对象方法赋值给一个变量来调用呢

1
var sayHi = person.sayHi;
2
sayHi();

此时会输入 Window 你好,我是,今年undefined岁.
因为当我们 person.sayHi 赋值给 sayHi, 调用 sayHi() 是在全局下,此时 this 指向全局对象,所以找不到name和age

单独使用

1
console.log(this)  // Window

函数中使用

1
function f1(){
2
    "use strict";
3
    console.log(this)   // undefined
4
}
5
f1();
1
function f1(){
2
    console.log(this)   // Window
3
}
4
f1();

call

1
var man = {
2
  name:'李四',
3
  age:45,
4
}
5
person.sayHi.call(man);  // 你好,我是李四,今年45岁

输出 this 变成了 man 对象。

箭头函数中的this

箭头函数没有自己的this,箭头函数的this就是上下文中定义的this.

1
var name = 'JavaScript';
2
var book =  () => {
3
        console.log(this);
4
        console.log(this.name)
5
    }
6
book()

输出 JavaScript。
对于 book 函数,它本身没有this值,而是使用外层的this。最外层的是 Window 对象。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!