function bind(method, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { var a = args.concat(Array.prototype.slice.call(arguments, 0)); return method.apply(context, a); } } Closed due to the fact that it is necessary to reformulate the question so that it was possible to give an objectively correct answer by the participants aleksandr barakin , Kromster , Cheg , Eugene Krivenja , Alex 27 Sep '17 at 16:42 .
The question gives rise to endless debates and discussions based not on knowledge, but on opinions. To get an answer, rephrase your question so that it can be given an unambiguously correct answer, or delete the question altogether. If the question can be reformulated according to the rules set out in the certificate , edit it .
- oneWhy do you copy tasks from a textbook or an exam ticket? A normal, lively person will never write like that. - VladD
- one@VladD is a variant of writing your bind. It looks like a completely working code, except that the name of the variable "a" is inconvenient for perception. It can be used, as I wrote in the answer below, in ancient browsers (when there is no such function at all), or when it is necessary to expand the functionality of the built-in functions (or there is no confidence in them and a samopisny library is used). - Psijic
1 answer
Functions in JavaScript are not tied to their this context, on the one hand, it’s great - it allows you to be as flexible as possible, lend methods and so on.
But on the other hand - in some cases, the context may be lost. That is, we sort of call the object method, but in fact it gets this = undefined.
As a result of calling bind (func, context), we get a “wrapper function” that transparently passes the call to func, with the same arguments, but with a fixed context.
The analog bind for IE8 and older versions of other browsers will look like this:
function bind(func, context /*, args*/) { var bindArgs = [].slice.call(arguments, 2); // (1) function wrapper() { // (2) var args = [].slice.call(arguments); var unshiftArgs = bindArgs.concat(args); // (3) return func.apply(context, unshiftArgs); // (4) } return wrapper; } It works like this (line by line):
- Calling bind saves additional args arguments (they come from the 2nd number) to the bindArgs array.
- ... and returns the wrapper wrapper.
- This wrapper makes the arguments array from arguments, and then, using the concat method, adds them to the bindArgs arguments (curring).
- It then passes the call to func with a context and a common argument array.