View Single Post
Old 11-21-2012, 08:14 AM   PM User | #6
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,468
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by rnd me View Post
@felgall - sorry about the hijacking. i was just going to mention .bind() and be on my way, but i obviously got carried away again. it happens, and i think this is good info and related to your idea, so i won't delete it.
I don't see how you hijacked the thread with your suggestion. As you said it is good info and definitely related to what I posted.

The part you didn't cover is why call and apply (and bind) have that first parameter. The original intention for those Function methods is to allow a method attached to one object to be borrowed by a different object. The first parameter is the object that is borrowing the method from the one that is being called in the code. It just happens that in each of the examples that we have posted here that we are borrowing the method to use as a function rather than as a method attached to a different object. Since the code we are calling makes no reference to "this" it doesn't care what is in that first parameter. Where the function being called - max() in my example - doesn't contain any references to the "this" it doesn't matter what you place in the first parameter as the object that the non-existent "this" references are to refer to. The advantage apply() has in situations like in my original post is that it takes care of converting an array into an arguments list for you in the same way that var args = Array.prototype.slice.call(arguments); converts arguments into an array. (you can of course shorten both ways using bind).

You can also use apply when you have nested functions and want to pass the arguments passed to the outer function directly into the inner function.

Example 8.5 on page 189 of the book "JavaScript: The Definitive Guide" 6th Edition has code to add Function.prototype.bind for those browsers that don't support it natively. There are a couple of minor differences that the text on the page lists but the supplied code ought to allow most of the uses for bind() that you can think of in the older browsers - so there is no reason to avoid using it just because some of your visitors are using those older browsers.

Just one extra point - If you use 0 as the second parameter in the bind for Math.max.apply then you eliminate the possibility of the maximum being negative. That second parameter should be Number.NEGATIVE_INFINITY in order to allow the maximum to be negative.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 11-21-2012 at 08:59 AM..
felgall is offline   Reply With Quote