How to change the context of a function in javascript

前端 未结 6 1743
醉梦人生
醉梦人生 2020-12-13 19:24

I\'m trying to understand why in javascript, you might want to change the context of a function. I\'m looking for a real world example or something which will help me unders

6条回答
  •  长情又很酷
    2020-12-13 19:59

    A real world example that i've encountered:

    If you add a function as an event handler to a DOM element and if you use "this" inside that function, "this" will refer to the DOM element that you added the event handler to.

    But that function might be a method of an object and you want the "this" keyword used inside it to refer to the owner object...so you need to change the context so that "this" will not refer to the DOM element but will refer to the owner object.

    You can easily change the context of a function in jquery using the proxy() function. See this question: jquery "this" binding issue on event handler (equivalent of bindAsEventListener in prototype) and the first answer

提交回复
热议问题