this的指向

50 阅读1分钟

Js的this指向

不同情况下的this指向?

(1)、全局作用域下:指向Window对象

console.log(this)  //Window

(2)、方法体内,this指向函数的调用者

//方法中
function fn() {
  return console.log(this) //Window,因为Window调用了fn() Window.fn()
​
}
fn() 
//对象方法中
const obj = {
    a: function () {
      console.log(this === obj) //true,因为对象调用的
    },
}
obj.a()

(3)、ES6 箭头函数的this指向父级作用域

//方法中
let fn = () => console.log(this) //Window,
fn()
​
//对象方法中
let obj = {
  fn: () => console.log(this) //Window
}
obj.fn()

(4)、定时任务:setTimeout中,this指向Window,因为都是Window调用的

 setTimeout(function () { 
     console.log(this)  //Window
 })
​
setTimeout(() => console.log(this), 0) //Window

(5) 、数组方法中,this指向Window

[1, 2, 3].forEach((item) => console.log(this)) //Window

(6)、点击事件中,普通函数this指向函数的调用者,箭头函数指向Window

<div></div>
//普通函数中
const a=document.querySelector('div')
  a.addListener('click',function(){
    console.log(this) //a
})
//箭头函数中
 window.onload = function () {
    const a = document.querySelector('div')
    a.addEventListener('click', () => console.log(this)) //Window
 }

this的指向能否修改?有几种方式?有什么区别

this可以改变this指向
有call、apply、bind三种方式
区别:
①call、apply可立即执行,bind不会立即执行,bind返回的是函数,需要调用才能执行 ②参数不同,apply第二个参数为数组,call、bind参数直接罗列即可

 function fn(a, b) {
         console.log(this === obj, a, b)
      }
    const obj = {}
    fn.call(obj, '张三', '李四')   //true '张三' '李四'
    fn.apply(obj, ['张三', '李四'])//true '张三' '李四'
    fn.bind(obj, '张三', '李四')() //true '张三' '李四'

有几种方式绑定this?这几种方式的优先级

有三种方式改变优先级

(1)、new方式 (函数通过new调用后,会返回一个新对象,并将新对象会绑定到函数调用的 this上。)

(2) 、显示绑定---call、apply、bind

(3)、 隐式绑定---全局作用域、普通方法、箭头函数、定时器....

优先级?

new 方式 >显示绑定 >隐式绑定