【JS基础】this

发布于:2024-08-13 ⋅ 阅读:(97) ⋅ 点赞:(0)

this

  • this的5种绑定方式
  1. 默认绑定(非严格模式下this指向全局,严格模式下函数内的this指向undefined)
  2. 隐式绑定(当函数引用有上下文对象,如obj.foo()的调用方式,foo内的this指向obj)
  3. 显式绑定(通过call或者apply方法直接指定this的绑定对象)
  4. new构造函数绑定,this指向新生成的对象
  5. 箭头函数,this指向的是定义时所在上下文的this值,箭头函数的this在定义时就决定了,不能改变
"use strict";
var a = 10; // var定义的a变量挂载到window对象上
function foo () {
  console.log('this1', this)  // undefined
  console.log(window.a)  // 10
  console.log(this.a)  //  报错,Uncaught TypeError: Cannot read properties of undefined (reading 'a')
}
console.log('this2', this)  // window
foo();

注意:开启了严格模式,只是使得函数内的this指向undefined,它并不会改变全局中this的指向。因此this1中打印的是undefined,而this2还是window对象。

var obj2 = {
  a: 2,
  foo1: function () {
    console.log(this.a) // 2
  },
  foo2: function () {
    setTimeout(function () {
      console.log(this) // window 
      console.log(this.a) // 3
    }, 0)
  }
}
var a = 3

obj2.foo1()
obj2.foo2() 

对于setTimeout中的函数,这里存在隐式绑定的this丢失,也就是当我们将函数作为参数传递时,会被隐式赋值,回调函数丢失this绑定,因此这时候setTimeout中的this指向window

var obj = {
 name: 'obj',
 foo1: () => {
   console.log(this.name) // window
 },
 foo2: function () {
   console.log(this.name) // obj
   return () => {
     console.log(this.name) // obj
   }
 }
}
var name = 'window'
obj.foo1()
obj.foo2()()


箭头函数内的this是由外层作用域决定的


网站公告

今日签到

点亮在社区的每一天
去签到