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

330 阅读1分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。

一、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])