The first parameter to the bind
method is the new this
value. The problem is that this appears to replace the natural this
value. In particular, if used for an event listener, it is no longer the triggering element.
For example:
var h1=document.querySelector('h1')
h1.onclick=doit.bind(this,42); // or null, or h1
function doit(a) {
alert(this); // Not automatically the calling element
alert(a);
}
Now I know that in this case I can set the first parameter to the element h1
; I can also use event.target
to get the actual target. However that’s not always convenient, for example when assigning an event listener to multiple or anonymous elements.
The question is, is there a simple way to tell bind
to use the default value of this
?
Thanks
Note: This is not strictly a duplicate of Use bound this and this of function scope in a function bound with bind() as (a) The question asks whether it is possible to bind more than one version of this
and (b) The accepted answer involves either using event.currentTarget
which I sort of mentioned myself or writing a new method, which is not what I was asking.
However, it is possible that the answer is no, it can’t be done, so I won’t seek to re-open the question.