Object-oriented Javascript function overload and type check

Source: Internet
Author: User
  Function overload and type check

A common feature of other object-oriented languages (such as Java) is the ability to "overload" functions: pass them to different numbers or types of parameters, and the functions perform different operations. Although this capability is not directly available in JavaScript, the provision of some tools makes this exploration completely possible.
Each function in JavaScript contains a context-related variable named arguments. Its behavior is similar to a pseudo array and contains all the parameters passed to the function. The parameter is not a real array (meaning you cannot modify it, or call the push () method to add new items), but you can access it as an array, and it does have a length attribute. There are two examples in program 2-5.

Two examples of function overloading in programs 2-5. JavaScript

// A simple function for sending messages
Function sendMessage (msg, obj ){
// If a message and an object are provided at the same time
If (arguments. length = 2)
// Send the message to the object.
Obj. handleMsg (msg );

// Otherwise, it is assumed that only the message is provided
Else
// The message is displayed.
Alert (msg );
}

// Call the function with a parameter-display the message in the warning box
SendMessage ("Hello, World! ");

// Or, we can also input our own object using
// Display information in different ways
SendMessage ("How are you? ",{
HandleMsg: function (msg ){
Alert ("This is a custom message:" + msg );
}
});

// A function that uses any number of parameters to create an array
Function makeArray (){
// Temporary Array
Var arr = [];
// Traverse each submitted Parameter
For (var I = 0; I <arguments. length; I ++ ){
Arr. push (arguments [I]);
}
// Returned result Array
Return arr;
}

In addition, there is another method to determine the number of parameters passed to a function. This special method uses a little more skill: we use the fact that any passed parameter value cannot be undefined. The program 2-6 shows a simple function to display an error message. If it is not sent to it, a default message is provided.

Program 2-6: Display error messages and default messages

Function displayError (msg ){
// Check whether msg is not undefined
If (typeof msg = 'undefined '){
// If yes, set the default message
Msg = "An error occurred .";
}

// Display the message
Alert (msg );
}

The use of typeof statements introduces the type check. Because JavaScript (currently) is a dynamic language, this topic is particularly useful and important. There are many ways to check the types of variables; we will explore two very useful methods.
The first way to check the object type is to use the explicit typeof operator. This useful method gives us a string name that represents the type of the variable content. This would be a perfect solution unless the variable type or array or custom object such as user (in this case, it always returns "ojbect", making it difficult to differentiate various objects ).
For an example of this method, see Program 2-7.

Program 2-7. Example of determining the object type using typeof

// Check whether our number is actually a string
If (typeof num = "string ")
// If yes, parse it into numbers
Num = parseInt (num );

// Check whether our array is actually a string
If (typeof arr = "string ")
// If yes, use a comma to separate the string and construct an array
Arr = arr. split (",");

The second way to check the object type is to refer to a common property called constructor of all JavaScript objects. This attribute is a reference to a function originally used to construct this object. For examples of this method, see Program 2-8.

Example of using the constructor attribute to determine the object type

// Check whether our number is actually a string
If (num. constructor = String)
// If yes, parse it into numbers
Num = parseInt (num );

// Check whether our string is actually an array
If (str. constructor = Array)
// If yes, use a comma to connect to the array to obtain a string
Str = str. join (',');

Table 2-1 shows the results of the type check for different types of objects using the two methods described above. The first column of the table shows the objects we are trying to find. Run typeof Variable (Variable is the value shown in the first column ). All results in this column are strings. Finally, the third column shows the result of running Variable. constructor on the objects contained in the first column. All the results in these columns are objects.
Table 2-1. Variable type check
-------------------------------
Variable typeof Variable. constructor
-------------------------------
{An: "object"} object Object
["An", "array"] object Array
Function () {} function Function
"A string" string String
55 number
True boolean Boolean
New User () object User
----------------------------------
With table 2-1 information, you can now create a common function to perform type checks within the function. It may be obvious that using a variable's constructor as an object type reference may be the simplest type check method. When you want to determine the exact number of parameters to be passed into your function, strict type checks may be helpful. In program 2-9, we can see the actual example.
  
Program 2-9. A function that can be used to strictly maintain all input function parameters

// Strictly check the type of a Variable list based on the parameter list
Function strict (types, args ){

// Ensure that the number and type of Parameters match
If (types. length! = Args. length ){
// If the length does not match, an exception is thrown.
Throw "Invalid number of arguments. Expected" + types. length +
", Received" + args. length + "instead .";
}

// Traverse each parameter and check the base type
For (var I = 0; I <args. length; I ++ ){
// If a JavaScript type does not match, an exception is thrown.
If (args [I]. constructor! = Types [I]) {
Throw "Invalid argument type. Expected" +
Types [I]. name + ", received" +
Args [I]. constructor. name + "instead .";
}
}
}

// A simple function used to print out the user list
Function userList (prefix, num, users ){
// Ensure that the prefix is a string and the num is a number,
// And the user is an array
Strict ([String, Number, Array], arguments );

// Process num users cyclically
For (var I = 0; I <num; I ++ ){
// Display the information of a user
Print (prefix + ":" + users [I]);

Variable type check and parameter length check are simple concepts, but they can be used to implement complex methods and provide a better experience for developers and users of your code. Next, we will discuss the scope of JavaScript and how to better control it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.