一篇就够了,JavaScript中this的指向问题

1.直接输出的this指向window

 //直接输出指向window
        console.log(this);
 //output:window

2.全局非嵌套函数的this指向window,嵌套函数this的指向他的父级函数

  //全局函数输出this,指向window
        function fn(){
            console.log(this);
        }
        fn()
   //output:window
   //嵌套函数this的指向指向他的父级函数
           function F(){
            this.name = '李四'
            function test() {
                console.log(this.name);
            }
        }
         F()
    //output:李四

3.对象的方法输出this,指向这个对象

//对象的方法输出this,指向这个对象
        const dog={
            name:'旺旺',
            sayName(){
                console.log(this);
            }
        }
        dog.sayName()
 //output:旺旺

4.dom事件方法输出this,指向dom元素

//html:
<button id="btn">点我触发方法</button>
//js:
 //dom事件方法输出this,指向dom元素
        document.querySelector("#btn").onclick = function click() {
            console.log(this);
        }
 //output:<button id="btn">点我触发方法</button>

5.构造函数中this的指向:

如果把构造函数当成普通函数去执行的话,this还是指向window

function F(){
            this.name = '李四'
            console.log(this);
        }
        F()
  //output:window

如果用构造函数创建了一个对象,会改变其中this的指向:this会指向构造函数的原型对象

        function F(){
            this.name = '李四'
            console.log(this);
        }
        let f = new F()
    //output:F {name: '李四'} 
  • 在讲箭头函数的this指向之前,先看一个转换this指向的小例子
        const dog1={
            name:'旺旺',
            sayName(){
           		//sayName函数的this指向对象dogs的this,我们可以用_this做一个中转变量,
                _this = this
                setTimeout(function () {
                	//这里的_this就是对象dogs的this
                    console.log(_this.name);
                },1000)
            }
        }
        dog1.sayName()
    //output:一秒之后会输出:旺旺

6.箭头函数的this指向箭头函数的调用者

我们上面的小例子还可以用箭头函数的方式解决this的指向问题

 const dog2={
            name:'旺旺',
            sayName(){
                setTimeout(() => {
                    console.log(this.name);
                }, 2000);
            }
        }
        dog2.sayName()
   //output:一秒之后会输出:旺旺

因为箭头函数的this指向箭头函数的调用者:(sayName函数),因为sayName函数的this指向为对象dog2,所以箭头函数的this指向为对象dog2,所以上面函数一秒之后会输出:旺旺


谢谢大家的观看,如果有所收获请点个赞吧(拜谢,拜谢,拜谢)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值