Implementing Overloaded Methods

an article added by: Sonja Lande at 05312007


In: Root » » AJAX » Implementing Overloaded Methods

French Spanish Portuguese Italian German Japanese Chinese Korean Russian Arabic

You want to implement overloaded methods in your JavaScript code. When a method is assigned to any object, there can only be one instance of that property. It is not possible in JavaScript to assign multiple same-named properties. For example, the following code will not work.

   Source: /website/ROOT/ajax articles/javascript/overloaded.html
   var cls = new Object();
   cls[ "method"] = function() {
   info( "method1", "hello");
   }
   cls.method();
   cls[ "method"] = function() {
   info( "method2", "hello");
   }
 cls.method();

In the example code, there are two assignments to the method property. The cls.method method is called twice, and for each call the function implementation called is the last assignment value. The code is trivial and is meant to illustrate that you cannot overload a method by assigning it. Overloading a method is useful in situations where a variable number of parameters are going to be called on a method. Since there are no type declarations, overloaded methods will vary in the number of parameters. The logic used is that if the method is called with five parameters, then an overloaded method that processes five parameters will be called. If the overloaded method does not exist, the default implementation that was initially assigned to the property will be used. Solution The implementation of the overloaded method is as follows.

   Source: /website/ROOT/scripts/jaxson/common.js
   overloaded : function(instance, funcIdentifier,  newFunc) {
   var overloadedPrototype = function() {
   var embeddedFunc = __embedded;
   var overloadedFunc = __newFunc;
   if (arguments.length == __paramCount) {
   overloadedFunc.apply(this, arguments);
   }
   else if (typeof(embeddedFunc) ==  "function") {
   embeddedFunc.apply(this, arguments);
   }
   }
   var origFunc;
   if (!instance[funcIdentifier]) {
   origFunc = function() { };
   }
   else {
   origFunc = instance[funcIdentifier];
   }
   instance[funcIdentifier] =  Generics.expand(overloadedPrototype,
   {
   __embedded : origFunc,
   __newFunc : newFunc,
   __paramCount : ParamCount(newFunc)
   });
 },

In the implementation, JavaScript generics are used to expand the overloadedPrototype function. But added to this expansion is a twist not used previously. Look at the __paramCount identifier. If the identifier is cross-referenced, then __paramCount when it is expanded will reference a numeric value. This means that the expanded function will be hard-coded, but because JavaScript generics are used, this is not a bad thing. The performance will be faster because there is no need to calculate the number of parameters that the overloadedFunc function has. To use the overloaded method, the following code is used:

   function FunctionNoParam() {
   }
   function FunctionOneParam(param) {
   info("FunctionTwoParam",  "param=" + param);
   }
   function FunctionTwoParam(param1, param2) {
   info("FunctionTwoParam", "param1="  + param1 + " param2=" + param2);
   }
   var cls = new Object();
   cls.value = "original";
   cls.example = function() { info(  "default", "hello"); }
   ops.overloaded(cls, "example",  FunctionNoParam);
   ops.overloaded(cls, "example",  FunctionOneParam);
   ops.overloaded(cls, "example",  FunctionTwoParam);
   cls.example("one param example");
 cls.example("first param",  "second param");

Three functions are defined: FunctionNoParam, FunctionOneParam, and FunctionTwoParam. These functions serve as overloaded functions with a varying number of parameters. The cls variable is a generic JavaScript object with no methods or parameters. The data member value is assigned dynamically to the default method. After the default has been assigned, the method example is overloaded with the three overloaded functions using the ops.overloaded function. Once the methods have been overloaded, they can be called with a varying number of parameters. The overloaded methods, for example, will then sequentially find the correct method to call. When implementing overloaded methods, keep the following points in mind:

• The overloaded method JavaScript generics expansion was similar to that shown in previous articles. The only additional twist was the hard-coding of the parameter count. Using traditional programming practices, you would not do that, but using JavaScript

generics it is trivial and recommended.

• When overloading methods, you need to provide a default implementation if you want it.

• You need to support not only the number of parameters to determine what you want to call, but also the type. This is a much more common use case, after all. A method that accepts a string could be overloaded by a variant that accepts an array and calls the string version for each element.

• Overloading methods is not possible according to types, but is made according to parameter count.

• You could implement overloaded types that filter on specific types. For example, you could implement an overloaded method filter that queries the presence of a specific object value. To do that, you can combine the proxy with the overloaded articles. Dynamic Content articles When building Ajax applications, you’re creating user interfaces that interact with the data on the server side. Building a user interface includes multiple aspects that could be considered unrelated. For example, it requires a number of elements on a form. You need to place these elements properly and verify them. The placing and verification could be considered unrelated, because verification can proceed regardless of how the elements are placed, and vice versa. This article doesn’t attempt to dig through the details of how to place elements so that their usability is correct. Instead, this article digs through topics that focus on algorithms such as element verification, HTML dialog box generation, and dynamic layout generation.

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. Understanding the Definition and Philosophy of Ajax
The focus of this article is to provide solutions to some common, general problems and questions that are bound to arise before or during development of Asynchronous JavaScript and XML (Ajax) and Representational State Transfer (REST) applications. These common questions are not always technical in nature, often leaning more toward theory or philosophy of development. The problem with these kinds of questions is that once you begin to think about them, you keep going in a circle and end up where you star...

2. Understanding the Definition and Philosophy of Web Services and SOA
Understanding the Definition and Philosophy of Web Services and SOA Wikipedia offers the following definition of Web services:4 The W3C defines aWeb service as a software system designed to support interoperable machine-to-machine interaction over a network. This definition encompasses many different systems, but in common usage the term refers to those services that use SOAPformatted XML envelopes and have their interfaces described by WSDL. For ex...

3. Understanding the Definition and Philosophy of REST
Understanding the Definition and Philosophy of REST REST is a controversial topic among Web service enthusiasts, because it’s considered to stand for the opposite of what Web services and SOA are trying to achieve. The problem with this thinking is that REST is not in contradiction with the abstract definition of SOA and Web services. REST is in contradiction with technologies such as SOAP, WSDL, and WS-* specifications. The following offers a quick definition of REST:...

4. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

5. 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...

6. 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 ...

7. 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...

8. 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...

9. 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...

10. 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...