this.a()a.call(this)As I understand:
this.a() is a method of this.MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Any other difference? What are your best practices when using these two options?
Don't use a.call(this) when you can do this.a(), it makes things harder to understand and AFAIK you don't gain anything by doing this...
call and apply are useful when you want to use a method from another "class" but with your this parameter, such as:
var nodes = document.querySelectorAll('a') ;
Array.prototype.forEach.call(nodes, callback) ;
You can't use nodes.forEach because nodes is a NodeList not an Array and thus do not have a forEach method, but you can do the above.
Another use of call is when you want to force the this instance on a callback method (e.g. when you are creating a plugin).
plugin.doSomething ('#id', function () {
// I would like 'this' to reference my HTMLElement here
}) ;
So in doSomething you could do something like:
function doSomething (selector, callback) {
var e = document.querySelector (selector) ;
// Whatever...
callback.call(e) ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With