Understanding javascript borrowing methods

There are many explanations on how to convert the arguments function to a real array.

But I was very interested when you simplify the code with bind .

MDN Array.prototype.slice - objects like an array

MDN Function.prototype.bind - Creating Shortcuts

For instance:

 function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] 

Simplified call:

 var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { return slice(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] 

It works the same if you use apply instead of call :

 var slice = Function.prototype.apply.bind(unboundSlice); 

Which can even be shortened using call from any instance of the function, as it is the same as in the prototype, and the same approach with slice from an array instance:

 var slice = alert.call.bind([].slice); 

You can try

 var slice = alert.call.bind([].slice); function list() { console.log(slice(arguments)); } list(1, 2, 3, 4); 

So, the first very strange thing that comes to my mind is to call bind on apply , but the first argument to bind should be an object (as a context), and not a function ( Array.prototype.slice ).

Another is the same as with call and apply .

I have been writing javascript for quite some time and I use these methods every day with confidence, but I cannot wrap this topic around me.

Perhaps I am missing some very fundamental details.

Can someone give an explanation?

+5
source share
2 answers

the first argument to bind should be an object (as a context)

Yes.

not a function ( Array.prototype.slice ).

Why not? Firstly, all functions are objects, so there is nothing wrong with that.

On the other hand, if you use slice.call(…) or slice.apply(…) , then the slice object is the context (receiver) of calls to the call / apply method.

What is the difference between apply and call binding?

There is no difference between applyBoundToSlice(arguments) and callBoundToSlice(arguments) . The difference is applyBoundToSlice(arguments, [0, n]) vs callBoundToSlice(arguments, 0, n) if you want to pass the start and end arguments to slice .

+2
source

You can use the call keyword to implement method borrowing. The following is an example of a borrowing method.

 var john = { name: "John", age: 30, isAdult: function() { console.log(this.name+" age is "+this.age); if (this.age > 18) { return true; } else { return false; } } } console.log(john.isAdult()); var rita = { name: "Rita", age: 15 } console.log(john.isAdult.call(rita)); 

Follow the last line. How the call keyword is used and how the rita object is passed to the function.

0
source

All Articles