this详解

73 阅读1分钟

this 指向

介绍:this式是js中的一个关键字。

(谁调用this,this就指向谁)

全局使用

function test(){
    console.log(this)
}
​
window.test()//此处this由window调用

对象使用

var obj={
    name:"kerwin",
    test:function(){
        console.log("11111",this)
    }
}
obj.test()

指向obj

特殊

计时器

setTimeout

setTimeout(function()
          {
    console.log(11111,this)
},2000)

屏幕截图 2023-11-13 185927.png

指向window

事件绑定this

dom0 类型

box.onclick=function(){
    console.log("1111")
}

缺点:重复绑定之后会覆盖掉前面的

dom2类型

可以绑定多个事件处理函数 按照顺序执行k

box.addEventListener("click",function()
                    {
    console.log("11111111")
})
box.addEventListener("click",function()
                    {
    console.log("22222222")
})
box.addEventListener("click",function()
                     {
    console.log("3333333")
})

dom0与dom2没有区别

evt和this的区别

例如

 box.addEventListener("click",function(evt){
    console.log(evt.target)
    console.log("1111".this)
 })

屏幕截图 2023-11-13 192214.png

点击时evt显示的是<span>

<this>则显示整个节点

改变this指向

call apply

obj1.getName.call(obj2)
obj1.getName.apply(obj2)
//将obj1改成obj2

call执行函数,并改变this执行为函数的第一个参数

支持多个参数

apply执行函数,并改变执行为函数的第一个参数

两个参数,第二个参数是一个数组

bind 改变this指向为函数的第一个参数,不会自动执行函数

var fun1=obj1.getName.bind(obj2,1,2,3)
console.log(fun1)
fun1()

应用场景:例如:点击按钮后才执行

与箭头函数的区别

function Person() {
  this.age = 25;
​
  // 普通函数,this 指向该函数的调用者(此处为 setTimeout)
  setTimeout(function() {
    console.log('普通函数: ' + this.age);
  }, 1000);
​
  // 箭头函数,this 继承自 Person() 函数的上下文
  setTimeout(() => {
    console.log('箭头函数: ' + this.age);
  }, 1000);
}
​
const person = new Person();
// 输出:
// 普通函数: undefined
// 箭头函数: 25  指的是父级作用域