Share via


How JScript Overloads Methods

When two or more JScript members (functions or properties) in a class have the same name but different signatures, they are referred to as "overloaded" functions (properties). The "signature" of a function is based on the number, type, and order of parameters it accepts. Two functions have the same signature if they accept the same number of arguments, with the same type, in the same order. Functions that accept the same types of arguments in a different order, or functions that have a different number of arguments or arguments of different types have different signatures. (Note that the names of the arguments have no effect on the signature). Static functions may also participate in overloading, but as with return types, the static status of a method does not affect its signature. Therefore, a static method with the same name as an instance method must have a different parameter list.

Processing Logic

When an overloaded function is called, the overloaded function whose arguments most closely match the passed arguments is called, depending on the actual types of arguments passed to the function. If the argument types match a particular overload exactly, then that overload is called. If the argument types do not match any overload exactly, a process of elimination determines which overload is called. The process of elimination is based on how easily actual types can be converted to the types in the available overloads. For more information, see Coercion in JScript. In this example, class MethodOverload has three overloaded methods named Greetings. The first overload takes no parameters, the second overload takes one parameter of a String type, and the third overload takes two parameters: a String type and an int type.

var methodOverload = new MethodOverload();
methodOverload.Greetings();
methodOverload.Greetings("Mr. Brown");
methodOverload.Greetings(97, "Mr. Brown");

class MethodOverload
{
   function Greetings()
   {
     print("Hello, and welcome!");
   }
   function Greetings(name : String)
   {
     print("Hello, " + name + "!");
   }
   function Greetings(ticket : int, name : String)
   {
     print("Hello, " + name + "! Your ticket number is " + ticket + ".");
   }
}

The output of this program is:

Hello, and welcome!
Hello, Mr.Brown!
Hello, Mr.Brown! Your ticket number is 97.

See Also

Other Resources

JScript Language Tour

JScript Data Types