Defining and Extending Classes

an article added by: Sonja Lande at 05312007


In: Root » Computers and technology » AJAX » Defining and Extending Classes

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

Defining and Extending Classes

Problem You want an effective strategy for defining and extending classes. Theory A function is an object, and as previous recipes illustrate, it is possible to associate properties and methods with a function. So why it is necessary to create classes, since functions can be morphed into classes? The answer relates to the problem of figuring out the instance of the function. Using JavaScript closures you can define a function within a function, as shown in the following code.

    Source: /website/ROOT/ajaxrecipes/javascript/functionsareobjects.html
    function GetFunctionFixed() {
    var inst = function(cmpval) {
    assertEquals(cmpval, inst.value);
    }
    return inst;
 }

By using a local variable, the instance of the function can be referenced within the implementation of the function. This works because functions are objects, and thus object referencing is happening. Solution Using the principle that functions are objects, it is possible to create a class without using the new keyword, as illustrated by the following example, which builds on the function within function technique.

    Source: /website/ROOT/ajaxrecipes/javascript/definingextendingclasses.html
    function CreateClassInstance() {
    var inst = function() {
    inst.instantiated = 10;
    inst.method = function() {
    inst.instantiated = 20;
    }
    }
    inst();
    return inst;
 }

In the class example, a “class” is created because calling the function will assign the properties of the function. Thus the function behaves like a “class.” The variable inst is referenced throughout the “class,” making it possible to reference the properties and methods of the “class.” In effect, the “class” is acting like a real class, as evidenced by the following test code.

    Source: /website/ROOT/ajaxrecipes/javascript/definingextendingclasses.html
    function_are_classes : function() {
    var cls1 = CreateClassInstance();
    info( "function_are_classes", cls1);
    cls1.value  = 10;
    assertEquals( 10, cls1.instantiated);
    cls1.method();
    assertEquals( 20, cls1.instantiated);
    var cls2 = CreateClassInstance();
    assertEquals(  "undefined", typeof( cls2.value));
 },

The test code experiments with various facets to demonstrate that the instantiated “object” is behaving like an object. The bold code shows that the “objects” cls1 and cls2 are in fact two separate instances. Since it seems so easy to create a “class” and an “object,” why is there a new keyword? The answer is because figuring out how to cross-reference the function instance with the method is complicated after the “class” has been instantiated, as illustrated by the following source code.

    Source: /website/ROOT/ajaxrecipes/javascript/definingextendingclasses.html
    function_classes_generates_error : function() {
    var cls = CreateClassInstance();
    cls.method2  = function() {
    inst.instantiated  = 40;
    }
    try {
    cls.method2();
    testManager.failed();
    }
    catch( e) {
    info(  "functions_classes_generates_error", "Expected exception ("  +➥
    e.toString() + ")");
    }
 },

In the additional test, the “class” is instantiated and assigned to the cls variable. The cls variable references an “object” that is extended with the method2 method. In the implementation of method2, the “object” instance is referenced using the inst variable. The inst variable was chosen because it was defined when the “object” was instantiated. Running the code will generate an exception because inst is not defined. To make the example work, the function referenced by method2 would have had to reference cls. In a nutshell, referencing the instance of the “object” within a function is more complicated than it ought to be. The solution is the new keyword, as it associates the this identifier with the instance of the object from within a function. Rewriting the CreateClassInstance code to use the new keyword, we arrive at the CreateRealClassInstance function, shown in the following code.

    Source: /website/ROOT/ajaxrecipes/javascript/definingextendingclasses.html
    function CreateRealClassInstance() {
    var inst = function() {
    this.instantiated = 10;
    this.method = function() {
    this.instantiated = 20;
    }
    }
    return  new inst();
 }

Comparing CreateClassInstance and CreateRealClassInstance, the only real difference is that the new keyword is used while calling the inst variable as a function, and inst is replaced with this. Using the new keyword in front of a function converts the function into a custom object instance, where the instance of the object can be referenced using the this identifier within the function. The returned object instance can be extended and the instance referenced using the this keyword, as shown in the following test.

    Source: /website/ROOT/ajaxrecipes/javascript/definingextendingclasses.html
    function_instantiates_real_class : function() {
    var cls = CreateRealClassInstance();
    cls.method2 = function() {
    this.instantiated = 40;
    }
    assertEquals(10, cls.instantiated);
    cls.method2();
    assertEquals(40, cls.instantiated);
 },

Calling the CreateRealClassInstance function, the returned object instance is assigned to the cls variable. The object is expanded to include the method2 method, and in the implementation of method2 the object instance is referenced using the this variable. This time when method2 is called, there is no exception and the instantiated property has a value of 40. If you are familiar with JavaScript and have already instantiated a few objects, then the previous instantiation syntax likely looks a bit odd. The classical way of instantiating an object in JavaScript is as follows:

    function MyObject() { }
 var cls = new MyObject();

This approach involves defining a function where the function is a constructor for the object of type MyObject. When MyObject is instantiated, the notation is very similar to instantiating a type in Java and C#, and therefore programmers who instantiate types in JavaScript never question what really happens. A more accurate explanation of how an object in JavaScript is defined is when the inst variable was used to instantiate an object. Specifically, an object is constructed by converting a function into an object, and the function associated with the new keyword is the constructor. When manipulating JavaScript classes, keep the following points in mind:

• It is possible to create JavaScript types without using the new keyword. However, creating raw JavaScript “objects” has the disadvantage of having to cross-reference the “object” instance with the function.

• JavaScript objects are types that you can assign dynamically, making it possible to implement prototype-based programming, where the behavior of the type is determined at runtime.

• Earlier recipes in this article showed how to manipulate function objects, a technique that also applies to JavaScript object types.

• The basis of all JavaScript objects is the type Object.

• When using the new keyword to instantiate a type, the prototype property associated with the function object can be used to define behavior that applies to all instances of a particular type.

legal disclaimer

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

related articles

1. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

2. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

3. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...

4. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...

5. Advantage of parameterless functions in JavaScript
Using Parameterless Functions Problem You want to take advantage of parameterless functions in JavaScript. Theory JavaScript functions for the most part have parameters. You may think that the previous sentence states the obvious after all, without parameters, what data could be passed to a function? JavaScript has the ability to declare functions that have no parameters, even though the caller of the function has passed parameters to the function. For example, let’s look at...

6. JavaScripot Functions
Treating Functions Like Objects Problem You want to take advantage of the fact that functions are objects (remember, everything is an object in JavaScript). Theory Many people think that a function is some keyword used in JavaScript. A function is also an object that can be manipulated. Knowing that a function is an object makes it very interesting from the perspective of writing JavaScript code, because the code can treat the function like another other object. This mean...

7. Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to ...