Regarding the problem of modifying the point of This

To modify this point
, call(), apply(), and bind() are commonly used
to discuss this topic as soon as I saw such a topic:

封装一个函数 abc,使这个abc指向指定的对象

function bindThis(abc, oTarget) {
    
    
    }

call() method

First, we first use call () to change this point

function bindThis(abc, oTarget) {
    
    
 	return function(x,y){
    
    
    return abc.call(oTarget,x,y)
}
    }

Why is there an anonymous function, because apply call is called immediately after binding, so it needs to be wrapped by an anonymous function and needs to be passed in the parameter argumengts of the original function. bind will create a new function, that is, a copy of the function

apply() method

这里要说明一下,call和apply都是立即执行的,而bind则是返回一个改变了上下文的函数副本

function bindThis(abc, oTarget) {
    
    
 	return function(){
    
    
    return abc.apply(oTarget,arguments)
}
    }

Does it feel similar and dissimilar to the call method? When I was writing, I also thought about it. Why not just change the call method variable to arguments?
I tried it and it didn't work, return abc.call(oTarget,arguments)and an error would be reported. I don't understand it very well, I hope someone can help me explain it.

bind method

function bindThis(abc, oTarget) {
    
    
        return abc.bind(oTarget)
    }

When using bind here, there is no need to use a function to encapsulate it, because after the bind function is bound, it will return a copy of the bound this function, and the original function will not change.

I have just cited three examples of these three methods. Of course, there are still many ways to expand, and everyone is welcome to communicate in the comment area. If you like it, you can click three consecutively~

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/112972804