Wrap a js function with a fixed this arg If I use node.addEventListener('click',Wyg.Editor.nodeClickedEvent); then when node is clicked, nodeClickedEvent has this===node. Since nodeClickedEvent is a static function in a class, I want this to === Wyg.Editor, so I wrote a helper function to simplify it.

Helper Function:

function fixThisFunc(object,functionName){
    const fixedFunc = function(){
        object[functionName].apply(object,arguments);
    };
    return fixedFunc;
}


How it's used:  

let node = document.getElementById('myFavoriteNode');
node.addEventListener('click', fixThisFunc(Wyg.Editor,'nodeClickedEvent'));


How it looked before:


node.addEventListener('click',
    function(event){
        Wyg.Editor.nodeClickedEvent(event);
    }
);



The Wyg.Editor class is like:

Wyg.Editor = class {

    static nodeClickedEvent(event){
        const clickedNode = event.target;
        console.log(this); //successfully outputs the Wyg.Editor object/class
        this.getEditableNode(clickedNode);
    }
//there are more functions, of course
};


I'm looking for a review of the Helper Function fixThisFunc

Are there any particular problems I should be worried about? is there a better way to achieve this functionality?
is there a better way to achieve this functionality?


You can use Function.bind() to create a function with the this context bound to Wyg.Editor:

const node = document.getElementById('myFavoriteNode');
node.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));


See this demonstrated in the snippet below.

Notice that const was used instead of let - unless there is a reason to re-assign node, use const. This will avoid accidental re-assignment.



const Wyg = {};
Wyg.Editor = class {

    static nodeClickedEvent(event){
        const clickedNode = event.target;
        console.log('nodeClickedEvent() - this: ', this); 
        
    }
};
const node = document.getElementById('myFavoriteNode');
node.addEventListener('click', Wyg.Editor.nodeClickedEvent.bind(Wyg.Editor));
&lt;button id="myFavoriteNode"&gt;click this favorite node&lt;/button&gt;