In Javascript, why is the “this” operator inconsistent?

后端 未结 8 1774
挽巷
挽巷 2020-11-22 15:04

In JavaScript, the \"this\" operator can refer to different things under different scenarios.

Typically in a method within a JavaScript \"object\", it refers to the

8条回答
  •  渐次进展
    2020-11-22 16:00

    As soon as callback methods are called from other context I'm usually using something that I'm call callback context:

    var ctx = function CallbackContext()
    {
    _callbackSender
    ...
    }
    
    function DoCallback(_sender, delegate, callbackFunc)
    {
     ctx = _callbackSender = _sender;
     delegate();
    }
    
    function TestObject()
    {
       test = function()
      {
         DoCallback(otherFunc, callbackHandler);
      }
    
      callbackHandler = function()
    {
     ctx._callbackSender;
     //or this = ctx._callbacjHandler;
    }
    }
    

提交回复
热议问题