Function

Prototype takes issue with only one aspect of functions, really: binding.

 

On this page

 

·What is binding?
·Say what?
·Prototype to the rescue!
·Moduleindex

 

 

 

What is binding?

 

“Binding” basically determines the meaning, when a function runs, of the this keyword. While there usually is a proper default binding (this refers to whichever object the method is called on), this can be “lost” sometimes, for instance when passing a function reference as an argument.

 

 

Say what?

 

Here’s an example:

 

  var obj = {

    name: 'A nice demo',

 

    fx: function() {

      alert(this.name);

    }

  };

 

  function runFx(f) {

    f();

  }

 

  window.name = 'I am such a beautiful window!';

 

  obj.fx();      // This works fine, displaying "A nice demo."

  runFx(obj.fx); // This goes awry, displaying "I am such a beautiful window!"

 

 

The reason why the second invocation boinks is: passing obj.fx as a regular function reference loses its binding to obj. It reverts to runFx’s default binding, which is the window object.

 

 

Prototype to the rescue!

 

Prototype solves this. You’ll find two new methods on any function: one that guarantees binding (it can even guarantee early parameters!), and one that is specific to functions intended as event handlers. See the list below.

 

 


Moduleindex

 

 

bind

 

bind(thisObj[, arg...]) -> Function

 

Provides a guaranteed-binding equivalent of the original function, possibly with pre-filled arguments.

 

bindAsEventListener

 

bindAsEventListener(thisObj[, arg...]) -> Function

 

An event-specific variant of bind, which makes sure the function will get the current event object as first argument.

 

 


Prototype API 1.5.0 - prototypejs.org