Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.a() vs a.call(this) in javascript [closed]

Tags:

javascript

  1. this.a()
  2. a.call(this)

As I understand:

  • In both cases the context will be this.
  • The first option can only be used when a() is a method of this.
  • When searching the codebase, two options of calling the same thing makes things more complex.

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?

like image 756
Lavi Avigdor Avatar asked Oct 18 '22 19:10

Lavi Avigdor


1 Answers

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) ;
}
like image 147
Holt Avatar answered Nov 15 '22 03:11

Holt