Next: , Previous: Hacking Around the Issue of Encapsulation, Up: Visibility Implementation


B.2.3 The Visibility Object

Let's consider how we may rewrite Stack in Figure B.10 using ease.js:

var Stack = Class( 'Stack',
{
    'private _data': [],

    'public push': function( val )
    {
        this._data.push( val );
    },

    'public pop': function()
    {
        return this._data.pop();
    }
} );

var inst = Stack();
inst.push( 'foo' );
inst.pop(); // foo

Figure B.11: Stack implementation using ease.js

The above implementation is much less impressive looking than our prior examples. What we have done is encapsulate the excess logic needed to emulate a class and got right down to business. ease.js will take the class definition above and generate an object much like we had done in the prior examples, with a few improvements.

If you have not read over the previous sections, you are recommended to do so before continuing in order to better understand the rationale and finer implementation details.

The secret behind ease.js's visibility implementation (see Access Modifiers) is referred to internally as the visibility object (or, in older commits and some notes, the property object). Consider the problem regarding the verbosity of our private property accessors and method calls in Figure B.10. It would be much more convenient if the properties and methods were bound to this so that they can be accessed more naturally, as would be expected by a programmer familiar with classes in other Classical Object-Oriented languages (see Figure B.11). This can be done using call() or apply():

function getName()
{
    return this.name;
}

var obj = { name: "foo" };
getName.call( obj ); // "foo"

Figure B.12: Calling a function within the context of a given object

Figure B.12 demonstrates the concept we are referring to. Given an arbitrary object obj, we can call any given method (in this case, getName(), binding this to that object. This is precisely what ease.js does with each method call. To understand this process, we have to explore two concepts: the visibility object itself and method wrapping. We will start by discussing the visibility object in more detail and cover method wrapping later on (see Method Wrapping).