473,216 Members | 2,241 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,216 software developers and data experts.

method overloading

can we overload a javascript function with different argument?

example:

function a(a){}
function a(a,b){}
Jul 23 '05 #1
4 9298
John Smith wrote:
can we overload a javascript function with different argument?

example:

function a(a){}
function a(a,b){}


See for yourself:

<script type="text/javascript">
function doalert(a, b) {
alert('doalert#1 called');
}

function doalert(a) {
alert('doalert#2 called');
}

doalert(1,2);
</script>

You will see that the second definition of the doalert() function overrides
the first one, so the answer is no.

An alternative would be to use a variable number of arguments when calling a
function and decide what to do based upon the defined arguments.
JW

Jul 23 '05 #2
On 28/03/2005 09:31, John Smith wrote:
can we overload a javascript function with different argument?

example:

function a(a){}
function a(a,b){}


Not in the way other languages define method overloading, no. In the
case above, the function object created by the first function
declaration would immediately be replaced by the second.

There are a few approaches that can be useful, depending on what
you're trying to achieve. You give no details so I'll provide a quick
run through them and you can determine which is best. I'll apologise
now for the exceedingly artifical examples. :/

1) Optional arguments

If a method is defined as taking optional arguments, you can add
the defaults by taking advantage of ECMAScript's rather different
logical OR (||) operator:

function myFunction(a, b) {
b = b || 'default';
}

If the argument, b, evaluates to false (that is, zero (0), empty
string (''), null, undefined, or false), the second operand will
be assigned in its place.

If one of these "false" values is legal, but not the default, see
(3) for an alternative.

2) Overloading by number of arguments

The arguments object available within all functions contains all
arguments passed to the function as properties, and the number of
arguments in its length property. You can use the value of the
latter to change the behaviour of the function, and the former to
access any arguments that do not have a corresponding formal
identifier.

function myFunction() {var msg;
if(arguments.length) {
msg = arguments.length + ' arguments passed:\n';

for(var i = 0, n = arguments.length; i < n; ++i) {
msg += '\n' + arguments[i];
}
} else {
msg = 'No arguments passed!';
}
alert(msg);
}

3) Overloading by type of arguments

I sometimes use this approach when I want to allow a function to
take either a reference to an element, or its id attribute value.
You can examine the type of the argument using the typeof
operator:

function myFunction(element) {
if('string' == typeof element) {
element = document.getElementById(element);
}
if(element) {
/* ... */
}
}

If a function is called and an argument doesn't have a corresponding
value, it will be undefined with typeof evaluating to the string,
'undefined'. Returning to the example in (1), you might have an
argument which expects an integer. If the argument was unspecified,
you might want it to assume the value -1, but zero is legal. In that
case,

function myFunction(a, b) {
if('undefined' == typeof b) {b = -1;}
}
Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3
JRS: In article <Jw****************@text.news.blueyonder.co.uk>, dated
Mon, 28 Mar 2005 15:37:13, seen in news:comp.lang.javascript, Michael
Winter <m.******@blueyonder.co.invalid> posted :
1) Optional arguments

If a method is defined as taking optional arguments, you can add
the defaults by taking advantage of ECMAScript's rather different
logical OR (||) operator:

function myFunction(a, b) {
b = b || 'default';
}

If the argument, b, evaluates to false (that is, zero (0), empty
string (''), null, undefined, or false), the second operand will
be assigned in its place.


That means that if the default is not zero, etc., it is impossible to
give and get used a parameter which is zero, etc.

How about if (b==null) b = 'default' ? It should enable having a
default which is not zero, etc., and giving p parameter which is zero,
an empty string, undefined, or false - although not for a value which,
like that of var U , is undefined, which needs b===null .

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #4
On 28/03/2005 21:20, Dr John Stockton wrote:

[MLW:]
function myFunction(a, b) {
b = b || 'default';
}

[snip]
That means that if the default is not zero, etc., it is impossible to
give and get used a parameter which is zero, etc.
I thought I made that point (or at least a similar one) at the end of
that section?
How about if (b==null) b = 'default' ?
My later suggestion was the use of the typeof operator that, whilst
slower than a equality test with null, should be foolproof for all
situations.
not for a value which, like that of var U , is undefined, which needs b===null .


As null and undefined are of different types, undefined !== null.
You'd either want to use typeof or a strict comparison with an
uninitialised variable. Of course, if you don't care about early
browsers and pre-IE 5.5 (not likely), you could also use the undefined
keyword.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Daniel Gustafsson | last post by:
Hi there, hmm, I've just started with C# and I'm experimenting with method overloading. It seems like it's not possible to override method using return types, only parameters. Is that by design,...
9
by: Ryan Taylor | last post by:
Hello. I am trying to overload a method so that I have four possible working copies. The only difference between the four methods is what to search by and in what manner to return the results....
2
by: Iter | last post by:
Hi Guys, In my company, we have java application which is runing in unix platform, and we have web service application build by microsoft .net runing in IIS in microsoft windows 2000 platform....
1
by: Ratnakar .N | last post by:
HELLO, Please tell me the main difference between method overriding and method overloading Thank you
10
by: Mihai Osian | last post by:
Hi everyone, Given the code below, can anyone tell me: a) Is this normal behaviour ? b) If it is, what is the reason behind it ? I would expect the A::method(int) to be inherited by B. ...
11
by: placid | last post by:
Hi all, Is it possible to be able to do the following in Python? class Test: def __init__(self): pass def puts(self, str): print str
5
by: Andreas Schmitt | last post by:
I have a problem here. I've read a book about C# already and got the basics of how the language handles polymorphism I think but I ran into a problem here that I simply never even thought of as a...
1
by: Zach | last post by:
Consider the following code: void Test(int i) { System.Console.WriteLine("int function"); } void Test(object o) { System.Console.WriteLine("object function");
10
by: Matthew | last post by:
Am I correct in thinking there is no method/function overloading of any kind in any version of PHP? Thanks, Matthew
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.