Home > Web Front-end > JS Tutorial > Javascript object-oriented overloading_js object-oriented

Javascript object-oriented overloading_js object-oriented

WBOY
Release: 2016-05-16 18:28:11
Original
1682 people have browsed it

The previous sections talked about JavaScript object-oriented namespace, javascript object-oriented JavaScript class and JavaScript object-oriented private members and public members. You can Read the above first and then continue reading below.


If I define it like this:

Copy the code The code is as follows:

function getDate(){.....}
function getDate(date){.....}

Then the latter method will overwrite the previous one, although no error will be reported.

But we can indeed implement overloading. If you have used jQuery, you will have a deep understanding of it. For example, $("#btn").val() is to get the button with the id "btn" value, and $("#btn").val("Click Me") assigns a value to the button with the id "btn".


So how is JavaScript implemented (accurately speaking, it should be called "simulation")?
The answer is simple: arguments
arguments is a built-in object in JavaScript, which contains the actual parameters passed by the caller, but is not limited to the parameter list defined by the function declaration. When it is called, it is the same as an array. length attribute.
Let’s understand it as an “array” for the time being. We choose different implementations based on the length of the array and the type of its elements, thereby simulating overloading.
Please see the following example for details:

Copy code The code is as follows:

function getDate(){
if(arguments.length==0){
var date=new Date().toLocaleDateString();
return "You did not enter parameters, now time:" date;
}

if(arguments.length==1){
if(arguments[0].constructor ==Date){
return "The parameter you entered is of Date type, now The time is: " arguments[0].toDateString();
}
if(arguments[0].constructor ==String){
return "The parameter you entered is of type String, and now the time is: " arguments[0];
}
}

}

So we can call it like this:
Copy code The code is as follows:

getDate()
getDate(new Date())
getDate("Monday")

This achieves JavaScript overloading, but we found that this "implementation" is too reluctant. If there are too many parameters, it will be overwhelming and the code will be messy, with if{. ..} . So I don't recommend using such overloading in JavaScript.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template