Skip to main content

Close
Get the best research tool on the web today,and free!
Connect with people with common interests!

saved byMichael C. Harris on 2008-07-02

  • In short, for most OOP languages, binding is implicit. This is true in Java, C#, Ruby, Delphi, and C++
  • PHP and JavaScript do require you to explicitly state which object you’re accessing, even if it’s the current one
  • 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
  • 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
  • Binding-sensitive code patterns
  • 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
  • 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
  • The only way to achieve this requires us to wrap our original method in another one, that will perform the apply call
  • 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
  • JavaScript frameworks do it
  • var that = this
  • that.
  • This code uses a language feature called “lexical closure.” In short, closures let code at point A access identifiers declared in scopes surrounding A
    • 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.