How to avoid “this” refering to the DOM element, and refer to the object

后端 未结 3 607
死守一世寂寞
死守一世寂寞 2021-01-16 11:48

I have a problem that I can\'t work around.

The context is: I want to have an inheritance chain, and a method of objects that belong to this inheritance has to be a

3条回答
  •  一生所求
    2021-01-16 12:46

    Simple. If a function is called as a method instead of "bare" the this always refers to the word before the last dot. So instead of:

    document.getElementById('myDiv').onclick = myObject.someHandler;
    
    // You're just passing the function here, not calling it.
    // It will be called by the onclick handler so `this` is changed
    

    do this:

    document.getElementById('myDiv').onclick = function(){
        myObject.someHandler();
    
        // Here, you're actually calling it. So this is the word
        // before the last dot. Which is myObject
    }
    

    In more modern javascript you can of course use bind:

    document.getElementById('myDiv').onclick = myObject.someHandler.bind(myObject);
    

提交回复
热议问题