0

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.

Community
  • 1
  • 1
Manngo
  • 14,066
  • 10
  • 88
  • 110
  • I found this question here: http://stackoverflow.com/questions/13851088/how-to-bind-function-arguments-without-binding-this/16400626 – Lynn Aug 16 '16 at 08:18
  • @Lynn Thanks for the link. Short answer is create your own version, which is what I have been doing in the past, or forego the method and do it the old way by assigning a function expression. – Manngo Aug 16 '16 at 08:47

0 Answers0