i have seen this code:
Function.prototype.bind = function (bind) {
var self = this;
return function () {
var args = Array.prototype.slice.call(arguments);
return self.apply(bind || null, args);
};
};
in some implementation on javascript and used for handle EventListener
element.addEventListener('mousedown', this.mykeydownhandler.bind(this), false);
can explain me this functionality
That’s just a homebrew implementation of the standard
Function.bindfunction:That should be wrapped with some sort feature detection so that it only gets used for browsers with a behind-the-times JavaScript engine.
The problem with just saying this:
Is that
this.mykeydownhandleris an unbound function and the value ofthisinside that function will be determined when it is called. So, ifmykeydownhandlerdepends on whatthisis then you won’t have the right context when the event is triggered. When you say this:using either the native
bindor the homebrew replacement in your question, thethisin theaddEventListenercall will be the same asthisinsidemykeydownhandler.