Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.bind vs Closure in Javascript : how to choose?

Tags:

As said here:

http://jqfundamentals.com/book/index.html

Closures can also be used to resolve issues with the this keyword, which is unique to each scope. This mechanism can be particularly useful when dealing with callbacks, though in those cases, it is often better to use Function.bind, which will avoid any overhead associated with scope traversal.

But it doesn't really say how to distinguish between the two cases. I don't understand in fact what the author means by "avoid any overhead associated with scope traversal." Can you explain?

like image 813
user310291 Avatar asked Jun 18 '11 15:06

user310291


1 Answers

Take a look at this line in the example in the link above

console.log(self.myName, this.myName); 

(with self = this; a couple of lines above). The closure defined outerFunction method, exists in a different scope that is why it has a different this value from the outerObj object. (self.myName!=this.myName)

Scope traversal means, when you are reaching to grab a value (variable,object) that exists in a different scope, therefore additional overhead is added (code becomes slower to execute).

Using bind, you 're calling a function with an existing scope, so that scope traversal does not take place.

like image 77
Pantelis Avatar answered Oct 20 '22 01:10

Pantelis