Skip to main content

A List Apart: Articles: Getting Out of Binding Situations in ...

Popularity Report

Total Popularity Score: 0

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Rank

Bookmark History

Saved by 11 people (2 private), first by anonymouse user on 2008-07-02


Public Sticky notes

In short, for most OOP languages, binding is implicit. This is true in Java, C#, Ruby, Delphi, and C++

Highlighted by digiqr

PHP and JavaScript do require you to explicitly state which object you’re accessing, even if it’s the current one

Highlighted by digiqr

This is the single most important issue with JavaScript binding—something I’ll refer to as “binding loss.” It happens whenever you’re accessing a method through a reference instead of directly through its owner object

Highlighted by digiqr

The method loses its implicit binding, and this stops referencing its owner object and goes back to its default value, which in this case is window

Highlighted by digiqr

Binding-sensitive code patterns

Highlighted by digiqr

Every JavaScript function is equipped with an apply method that allows you to call that function with specific binding (a specific this, if you will). It takes two arguments: the binding object, and an array of the arguments to be passed to the function

Highlighted by digiqr

When you do know exactly which arguments you want to pass, call may feel nicer, as it takes the arguments themselves, not an array of them

Highlighted by digiqr

The only way to achieve this requires us to wrap our original method in another one, that will perform the apply call

Highlighted by digiqr

That function, when called, will take our original method and invoke apply on it, passing:
  1. the original object’s binding (the variable named object), and
  2. whatever arguments were provided at call time, as an array

Highlighted by digiqr

JavaScript frameworks do it

Highlighted by digiqr

var that = this

Highlighted by digiqr

that.

Highlighted by digiqr

This code uses a language feature called “lexical closure.” In short, closures let code at point A access identifiers declared in scopes surrounding A

Highlighted by digiqr

  • Any member access must be qualified with the object it pertains to, even when it is this.
  • Any sort of function reference (assigning as a value, passing as an argument) loses the function’s original binding.
  • JavaScript provides two equivalent ways of explicitly specifying a function’s binding when calling it: apply and call.
  • Creating a “bound method reference” requires an anonymous wrapper function, and a calling cost. In specific situations, leveraging closures may be a better alternative.
  • Highlighted by digiqr