My favorites | Sign in
Logo
                
Search
for
Updated Jun 04, 2008 by mikesamuel
Labels: Phase-Design
FunctionSpecies  
defining and calling functions in Caja

Species of Functions

Caja distinguishes different kinds of functions since different functions can do different things.

Constructors are used to create new objects, and act as both class and factory. Constructors can chain to their superclass, and manipulate the created object's protected interface via this. Any named function that mentions this is a constructor.

function ClassName(a, b) {
  BaseClass.call(this, a);
  this.b_ = b;  // define a protected field
}

Methods are functions attached to a particular class that can manipulate the protected interface of instances of that class via this. Any unnamed function that mentions this is a method.

caja.def(ClassName, SuperClass, {
  setB: function (b) { this.b_ = b; },
  getB: function () { return this.b_; }
});

Simple-functions don't have access to any object's protected interface, but can do anything else. Any function that doesn't mention this is a simple-function.

function foo(x, y) { return x + y; }

Exophoric Functions are created by calling caja.xo4a on a simple-function. When an exophoric function is called as a method, the object the method is called on will bound to the simple-function's first parameter, and the actual arguments are bound to the remaining parameters. To emphasize the this-like nature of this first parameter variable, its conventional name is self.

node.addListener('click', caja.xo4a(function(self) { handleClickEvent(self.id); }));

acts like

node.addListener('click', function() { handleClickEvent(this.id); });

does in uncajoled JavaScript. The first form will work both cajoled and uncajoled. As a temporary hack (when warts mode flag is on), the second form will currently work cajoled as well, but will shortly need to be rewritten as the first form.

Calling Functions

A function can be declared any of the ways above, but calling is more flexible.

. . . Functions defined as can be . . .

Ctor Method xo4a Simple
Ctor YES NO NO YES
called Method NO YES YES YES
. as . Simple NO NO NO YES


Comment by davidsarah.hopwood, Jun 02, 2008

For security arguments against the presence of exophoric functions (either implicit or explicit) in the language, see http://groups.google.com/group/google-caja-discuss/browse_thread/thread/46ab872c230e97a3

.

With regard to the event handling example, note that an event handler in the DOM Level 2 API can refer to the node on which the handler was set using 'event.currentTarget', where event is passed in as an argument, and so there is no need to use 'this'. For browsers that don't support DOM Level 2 event handling (in other words, MSIE), it can be simulated.


Sign in to add a comment