⬆️ ⬇️

Bind, Call and Apply in JavaScript

From the translator:

Please note that the code given here may not be good practice. However, parsing the snippet from this post may be another reason to plunge into functional JavaScript.



Recently, I saw an elegant JS snippet in this tweet.

var bind = Function.prototype.call.bind(Function.prototype.bind); // #fp 


Looking at him, I was able to guess what he was doing. It turns xy(z) into y(x, z) . Rejoicing as a child, I showed it to my colleagues. They asked me what was going on here. I opened my mouth to explain and ... could not say a word. I turned around and left.



In most cases, looking at well-written code, you can easily guess what it does. Having some kind of experience in functional JavaScript, after reading “Functional JavaScript” and “JavaScript Allongé” (both are wonderful), I had no particular difficulty in reading it. But how to explain this code to someone without functional programming experience?



I decided to gradually figure out simple examples of what is happening here. The result was:

')

 //   ,       var context = { foo: "bar" }; // ,    «foo»  «this» function returnFoo () { return this.foo; } //       ,  undefined returnFoo(); // => undefined //         var bound = returnFoo.bind(context); //      bound(); // => "bar" // //   Function.prototype.bind. //   returnFoo —  ,    Function.prototype // //        // Call  apply        returnFoo.call(context); // => bar returnFoo.apply(context); // => bar //        context.returnFoo = returnFoo; context.returnFoo(); // => bar // //     // //  Array.prototype    slice. //         //      () [1,2,3].slice(0,1); // => [1] //   slice      var slice = Array.prototype.slice; // slice    . - ,  Array.prototype.slice //      «this»,     slice(0, 1); // => TypeError: can't convert undefined to object slice([1,2,3], 0, 1); // => TypeError: ... //     apply  call,       slice.call([1,2,3], 0, 1); // => [1] // Apply   call,       slice.apply([1,2,3], [0,1]); // => [1] //    .call  .   bind? // !    call   slice. slice = Function.prototype.call.bind(Array.prototype.slice); //  slice       slice([1,2,3], 0, 1); // => [1] // // , ?      -. // //     bind  , //     slice var bind = Function.prototype.call.bind(Function.prototype.bind); //  ,     . //  ?   call,  ,      //      . //      var context = { foo: "bar" }; function returnFoo () { return this.foo; } //     bind var amazing = bind(returnFoo, context); amazing(); // => bar // Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind 

Source: https://habr.com/ru/post/199456/



All Articles