this的指向以及更改方法

(一)this的指向

(1)普通函数的this指向,

谁调用指向谁,没有调用者的时候指向window

(2)箭头函数的this指向

箭头函数本身没有this,箭头函数中this的引用就是最近作用域中的this(父级的this),一层一层向外层寻找,直到找到有this的定义

注意:不适用箭头函数的有:构造函数,原型函数,dom事件函数等等

(二)更改this指向

(1)call()方法

call(thisArg,参数1,参数2),thisArg代表this指向谁,参数1参数2代表原本函数中的参数

例如:fn中的this原本指向window,用call方法将其更改为指向obj

const  obj={

            name:'小开心',

            age:21

        }

        function fn(x,y){

            console.log(this)

        }

        fn()

        fn.call(obj,1,2)

(2)apply()方法

也是调用函数apply(更改指向参数,参数数组)

注意:第二个参数必须以数组的形式传递,且函数中的形参依次代表数组的第一个值,第二个值等

 const  obj={

            name:'小开心',

            age:21

        }

        function fn(x,y){

            console.log(this)

            console.log(x,y)

        }

        fn()

        fn.apply(obj,[1,2])

apply()方法也可以用来求最大值

const arr=[12,23,45,34,22]

        const max=Math.max.apply(Math,arr)

        console.log(max)

 (3)bind()方法(重要)

注意:其不调用函数改变this指向,返回值为原函数只是this指向变了

 const  obj={

            name:'小开心',

            age:21

        }

        function fn(){

            console.log(this)

        }

         const fun=fn.bind(obj)

         console.log(fun)

猜你喜欢

转载自blog.csdn.net/qq_50582468/article/details/129671355