[JS]05.this的几种基本情况

257 阅读2分钟

1.this概述

  • 全局上下文中的this是window,块级上下文中没有自己的this
// 全局的this 是Window
// 严格模式下,this也是Window
// 块级上下文中,没有自己的this,用的是上级上下文中的this
console.log(this) //window
{
  let n = 12;
  console.log(this) // window
}
  • this:函数的执行主体(执行时才能确定)
    • 函数执行主体:谁把函数执行的
    • 执行上下文:在哪执行的

2.this的几种情况

2.1 事件绑定中

给当前元素的某个事件行为绑定方法,当事件触发,方法执行,方法中的this是当前元素本身。


 document.body.onclick = function() {
   console.log(this) // body
 }
 
 // DOM二级事件绑定
 document.body.addEventListener('click', function() {
   console.log(this) // body
 })
 
 // IE6~8中 DOM2 事件绑定
  document.body.attachEvent('click', function() {
   console.log(this) // window
 })

2.2 普通函数中

创建函数时并不能确定this,只有执行时,看谁是执行主体,才能确定this

  • 函数执行前没有.,this就是window,严格模式下是undefined
  • 函数执行前有.,this就是.前面的东西
  • 匿名函数(自执行函数/回调函数)如果没有经过特殊处理,则this一般都是window或者undefined,如果有特殊处理,以处理后的结果为准
    • 回调函数:把一个函数当成值传给另一个函数
/*
1. 普通函数
*/
function fn() {
  console.log(this)
}

let obj = {
  name: 'paul',
  fn: fn,
}

fn(); // this->window,严格模式是undefined
obj.fn(); // this->obj


/*
2. 匿名函数
*/

// 2.1 自执行函数,创建和执行一起

(function() {
  console.log(this) // Window/undefined
})();

// 2.2 回调函数

// 2.2.1
// 把一个函数作为值通过实参传递给另一个函数
function fn(callback){
  callback(); // 前面没点
}
let obj = {
  // sum: function(){}的es6简写
  sum() {
    console.log(this)
  }
}
obj.sum()  // this->obj
fn(obj.sum)  // this->window

// 2.2.2
setTimeout(function () {
  console.log(this) // this->window/undefined
}, 1000) 

// 2.2.3 forEach的回调
let obj = {name: 'xxx'}
let arr = [10, 20]
// 第二个参数为空 this->window/undefined
arr.forEach(function(item, index) {
  console.log(this)
})
// 第二个参数为obj this->obj 特殊处理
arr.forEach(function(item, index) {
  console.log(this)
}, obj)


// 2.2.4 括号表达式
let obj = {
  sum() {
    console.log(this)
  }
}
obj.sum(); // this->obj
(obj.sum)(); // this->obj
// 括号表达式:小括号中包含(多项),用逗号分割,结果只取最后一项,但是this会发生改变,this不是obj,而是winodw/undefined
// 一项相当于不写,不改变this
(10, obj.sum)();