JS基础之this的指向和this指向的改变方法

一、this的指向

1、普通函数调用

普通函数调用,this指向window

		function fn() {
            console.log(this); //window
        }
        fn() //  window.fn(),此处默认省略window
2、构造函数调用

构造函数调用,this指向实例化对象

		function Dog(type, name) {
            this.type = type;
            this.name = name;
            console.log(this); //this分别指向dog1,dog2
        }

        const dog1 = new Dog('德牧', '阿牧');
        const dog2 = new Dog('拉布拉多', '波比');
3、对象方法调用

对象方法调用,this指向该方法所属的对象

		const obj1 = {
            fn: function() {
                console.log(this);//obj1
            }
        }
        obj1.fn();
4、通过事件绑定的方法

通过事件绑定的方法, 此时 this 指向 绑定事件的对象,(事件源)

		var oBtn = document.querySelector('button');
        oBtn.onclick = function() {
            console.log(this); //btn
        }
5、定时器

定时器,this指向window

		setInterval(function() {
            console.log(this); //window
        }, 1000)
6、严格模式下,this指向undefined
		function fn3() {
            "use strict"
            console.log(this); //undefined
        }
        fn3()
7、箭头函数

箭头函数中,this指向父元素

		document.onclick = function () {  
            console.log(this);  // 此处this指向document
            setTimeout(function () {  
                console.log(this);   // 此处this指向window
            })
            setTimeout(() => {
                console.log(this);  // 此处this指向document
            })
        }

二、this指向的改变

1、call()

call()改变函数的this指向并且调用该函数,第一个参数表示要改变成的this指向,之后的参数表示函数的参数

		function fn2(n) {
            console.log(this); //改之前是window
            console.log(n);
        }
        // fn2(5)
        fn2.call(document, 5) //改变后指向变成document
2、bind()

bind()只会改变this的指向,并不会调用该函数(return了这个函数),用法和call()一样

fn2.bind(document, 5)() //#document,5

由于不会调用该函数,所以执行后需要自行调用一下

3、apply()

apply()改变this的指向,第二个参数要写成数组的形式,不然会报以下错误
在这里插入图片描述

正确写法:

fn2.apply(document, [5])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值