简体   繁体   中英

What's the equivalent of passing “this” to a function?

I have a function which is expecting "this" to be passed as a parameter but I would like to pass a different object without moving the trigger function, so currently I have this:

onclick="showCalendarControl(this);"

but instead I would like to do this:

onclick="showCalendarControl(document.getElementById('somethingelse'));"

This doesn't work as it stands, am I trying to do something impossible?

Try using the .bind() function. Docs

The first argument to bind will set the functions' this argument (replacing the default one), all other arguments are translated into parameters once the method is called.

Examples:

onclick="showCalendarControl.bind(this)"  //the this-statement inside of showCalendarControl will be the specified one

onclick="showCalendarControl.bind(something, this);" //this will be passed as first argument to showCalendarControl

Edit: After testing it out, it seems that .bind() doesn't work in the onclick handler. But your initial idea worked, or at least what I understood as your problem (passing document.getElementById result to your method)

 function showCalendarControl(obj) { obj.innerHTML = "YEY"; } 
 <body> <div id="something" onclick="showCalendarControl(document.getElementById('somethingelse'));">Click Me</div> <div id="somethingelse"></div> </body> 

If you want to bind the parameter to the function's this statement, you can try this (use of the call() function instead of my initial bind):

 function showCalendarControl() { this.innerHTML = "YEY"; } 
 <body> <div id="something" onclick="showCalendarControl.call(document.getElementById('somethingelse'));">Click Me</div> <div id="somethingelse"></div> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM