Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.prototype.apply.bind usages?

Tags:

javascript

I perfectly know the usages for :

Function.prototype.bind.apply(f,arguments)

Explanation - Use the original (if exists) bind method over f with arguments (which its first item will be used as context to this)

This code can be used ( for example) for creating new functions via constructor function with arguments

Example :

function newCall(Cls) {
    return new (Function.prototype.bind.apply(Cls, arguments));
 }

Execution:

var s = newCall(Something, a, b, c);

But I came across this one : Function.prototype.apply.bind(f,arguments) //word swap

Question :

As it is hard to understand its meaning - in what usages/scenario would I use this code ?

like image 944
Royi Namir Avatar asked Mar 11 '14 09:03

Royi Namir


1 Answers

This is used to fix the first parameter of .apply.

For example, when you get the max value from an array, you do:

var max_value = Math.max.apply(null, [1,2,3]);

But you want to get the first parameter fixed to null, so you could create an new function by:

var max = Function.prototype.apply.bind(Math.max, null);

then you could just do:

var max_value = max([1,2,3]);
like image 61
xdazz Avatar answered Sep 22 '22 23:09

xdazz