Sie sind auf Seite 1von 2

http://dmitrysoshnikov.

com/ecmascript/javascript-the-core/#closures
The main purpose of the bind method is to statically bind a this value for subsequent calls of a
function. As we considered in the ECMA-262-3 in detail. Chapter 3. This, a this value can vary
in every function call. So, the main purpose of the bind is to fix this issue which can appear
e.g. when we attach a method of an object as event handler of some DOM element. Using a
bound function we can always have a correct this value in the events handling.

var widget = {

state: {...},

onClick: function onWidgetClick(event) {

if (this.state.active) {

...
}

6
}

7
8

};

9
10

document.getElementById("widget").onclick = widget.onClick.bind(widget);

I used simple click event attaching in the example above via onclick method, but on practice
you can better use multiple listeners pattern using addEventListener or attachEvent.
However the goal of the example is to show how this value is predefined and bound to
the widget object inside theonclick method, and this.state property is available.

Partial application
Another purpose of the current bind implementation is a currying (or closer to mathematics
a partial application of a function). It is the technique of transforming a function of multiple
arguments to a chain of functions each with a single argument that produce at the end the same
result. Which means we can generate functions based on other functions, and some (or maybe
all) arguments of the new function can be predefined. And applying the new function with the
rest arguments (with the last part of arguments) forms a partial application of the function.

function foo(x, y) {

// partial

if (typeof y == "undefined") {

return function partialFoo(y) {

// complete

return x + y;

};

// complete

10

return x + y;

11

12
13
14

foo(10, 20); // 30
foo(10)(20); // 30

15
16
17

var partialFoo = foo(10); // function


partialFoo(20); // 30

The practical rationale of partial application can be the case when you often use a function with
the same (repeating from call to call) part of arguments. In such case it is convenient to
encapsulate these arguments, making a new partial function. Another good practical example
can be again attaching an event listener with bound this value and some bound data which will
be available at the activation of the listeners handler. As a simplest example of such bound data
can be event object itself. Theoretically, partial application is related with some mathematical
theorems and also with lambda calculus where functions have only one argument.

http://dmitrysoshnikov.com/ecmascript/javascript-the-core/#closures

Das könnte Ihnen auch gefallen