B.2.4 Method Wrapping
The visibility object (see The Visibility Object) is a useful tool for
organizing the various members, but we still need some means of binding it to a
method call. This is accomplished by wrapping each method in a closure that,
among other things1, uses apply() to forward the arguments to the
method, binding this to the appropriate visibility object. This is very
similar to the ES5 Function.bind() call.
The following example demonstrates in an overly-simplistic way how ease.js handles class definitions and method wrapping.2
/**
* Simple function that returns a prototype ("class"), generated from the given
* definition and all methods bound to the provided visibility object
*/
function createClass( vis, dfn )
{
var C = function() {},
hasOwn = Object.hasOwnProperty;
for ( name in dfn )
{
// ignore any members that are not part of our object (further down the
// chain)
if ( hasOwn.call( dfn, name ) === false )
{
continue;
}
// simply property impl (WARNING: copies by ref)
if ( typeof dfn[ name ] !== 'function' )
{
C.prototype[ name ] = dfn[ name ];
continue;
}
// enclose name in a closure to preserve it (otherwise it'll contain the
// name of the last member in the loop)
C.prototype[ name ] = ( function( mname )
{
return function()
{
// call method with the given argments, bound to the given
// visibility object
dfn[ mname ].apply( vis, arguments );
};
} )( name );
}
return C;
};
var vis = { _data: "foo" },
Foo = createClass( vis,
{
getData: function()
{
return this._data;
},
} );
var inst = new Foo();
// getData() will be bound to vis and should return its _data property
inst.getData(); // "foo"
Figure B.18: Basic "class" implementation with method binding
There are some important considerations with the implementation in Figure B.18, as well as ease.js's implementation:
- Each method call, unless optimized away by the engine, is equivalent to two
function invocations, which cuts down on the available stack space.
- The method wrapping may complicate tail call optimization, depending on the JavaScript engine's implementation and whether or not it will optimize across the stack, rather than just a single-depth recursive call.
- As such, for operations that are highly dependent on stack space, one may wish to avoid method calls and call functions directly.
- There is a very slight performance hit (though worrying about this is likely to be a micro-optimization in the majority of circumstances).
As mentioned previously, each visibility object is indexed by class identifier (see Visibility Object Implementation). The appropriate visibility object is bound dynamically on method invocation based on the matching class identifier. Previously in this discussion, it was not clear how this identifier was determined at runtime. Since methods are shared by reference between subtypes, we cannot store a class identifier on the function itself.
The closure that wraps the actual method references the arguments that were passed to the function that created it when the class was defined. Among these arguments are the class identifier and a lookup method used to determine the appropriate visibility object to use for binding.3 Therefore, the wrapper closure will always know the appropriate class identifier. The lookup method is also passed this, which is bound to the instance automatically by JavaScript for the method call. It is on this object that the visibility objects are stored (non-enumerable; see Instance Memory Considerations), indexed by class identifier. The appropriate is simply returned.
If no visibility object is found, null is returned by the lookup
function, which causes the wrapper function to default to this as
determined by JavaScript, which will be the instance that the method was invoked
on, or whatever was bound to the function via a call to call() or
apply(). This means that, currently, a visibility object can be
explicitly specified for any method by invoking the method in the form of:
‘inst.methodName.apply( visobj, arguments )’, which is consistent with how
JavaScript is commonly used with other prototypes. However, it should be noted
that this behavior is undocumented and subject to change in future releases
unless it is decided that this implementation is ideal. It is therefore
recommended to avoid using this functionality for the time being.4
Footnotes
[1] The closure also sets the __super() method
reference, if a super method exists, and returns the instance if this is
returned from the method.
[2] ease.js, of course, generates its own visibility objects internally. However, for the sake of brevity, we simply provide one in our example.
[3] See
lib/MethodWrappers.js for the method wrappers and
ClassBuilder.getMethodInstance() for the lookup function.
[4] One one hand, keeping this feature is excellent in the sense that it is predictable. If all other prototypes work this way, why not “classes” as created through ease.js? At the same time, this is not very class-like. It permits manipulating the internal state of the class, which is supposed to be encapsulated. It also allows bypassing constructor logic and replacing methods at runtime. This is useful for mocking, but a complete anti-pattern in terms of Classical Object-Oriented development.