Solved

Polymorphism --> (overloading) <--

Posted on 2002-05-15
13
443 Views
Last Modified: 2008-03-10
Hi all,

firstly let me point out this :

http://webreference.com/programming/javascript/professional/chap3/2/3.html

now for my question - my aim is simple, i want to have an object which has 2 methods of the same name, distinguished by their parameter list.. (like we do in Java - overloading)

From the article above i got the impression that this would be possible.. maybe it is not if you know better let me know :)

Heres a simple code snippet i wrote to show you what i mean:

<html>
<head>
<title></title><script language="JavaScript">

function person () { //define class - ignore the
     this.name
     this.surname
     this.age
}
person.prototype.setPerson = setPerson;

//define methods

function setPerson (name) {
     alert("setPerson(name) called");
}

function setPerson () {
     alert("setPerson() called");
}

// ok using them now..
var myPerson = new person();

myPerson.setPerson("Mehdi");
myPerson.setPerson();

</script>

</head><body bgcolor="#ffffff" text="#000000"></body></html>

Right ? So the result im expecting is 2 alert boxes, the first one saying "setPason(name) called" , and the second saying "setPerson() called".

Thanks,
0
Comment
Question by:mehdi
  • 6
  • 3
  • 2
  • +2
13 Comments
 
LVL 1

Author Comment

by:mehdi
ID: 7010577
i just read what i posted .. let me add that the result i get is "setPerson() called" both times..

Thanks

Mehdi
0
 
LVL 9

Expert Comment

by:AlfaNoMore
ID: 7010611
function person () { //define class - must declare each property of this object.
    this.name       = '';
    this.surname    = '';
    this.age        = '';
    this.setPerson  = new function(X) {setPerson(X);}
    return this;
}
/* person.prototype.setPerson = setPerson; */ // what's this doing? Person is not an object yet?

function setPerson (name) {
    alert('setPerson(' + name + ') called');
}

// ok using them now..
var myPerson = new person();
myPerson.setPerson('Mehdi');

I think this is about all you can do within JavaScript. Your early-binding technique would just confuse the hell out of JavaScript.

You could have a setPersonHandler(name) function?

function setPersonHandler(name) {
    if (name) {
        setPersonNamed(name);
    }
    else {
        setPersonUnnamed();
    }
}

As the arguments are optional in JavaScript, this would be my suggestion?
0
 
LVL 22

Accepted Solution

by:
CJ_S earned 80 total points
ID: 7010618
Not really. You set setperson to be a reference to setPerson(). Polymorphism means that you have an interface. An object can implement that interface and thus it does not matter which object you instantiate since that object will always comply with the correct interface.

Basically you have two object x and y, both contain the same functions and you can instantiate either of 'm and call the function Depending on the object you'll get a different result.

Javascript does support it to some extend. You cannot use true polymorphism as you can in object oriented languages.

Second thing is that when you call the function setPerson() WITH a parameter (setPerson("Mendhi")) it does not distinguish between functions.

The only way you can get your thing to work is by adding another function and change the names of your current functions.

<html>
<head>
<title></title><script language="JavaScript">

function person () { //define class - ignore the
    this.name
    this.surname
    this.age
}
person.prototype.setPerson = setPerson;

//define methods

function setPerson()
{
   if(setPerson.arguments>0)
        setPersonX(setPerson.arguments[0]);
   else
        setPersonY();
}

function setPersonX (name) {
    alert("setPerson(name) called");
}

function setPersonY () {
    alert("setPerson() called");
}

// ok using them now..
var myPerson = new person();

myPerson.setPerson("Mehdi");
myPerson.setPerson();

</script>

</head><body bgcolor="#ffffff" text="#000000"></body></html>
0
 
LVL 1

Author Comment

by:mehdi
ID: 7010639
Alfa..

person.prototype.setPerson = setPerson; is my preferred way of declaring a method thats all.

Im not interested in writing one method and testing for inputs at the moment, i'd like to be convinced that nobody knows how to do this the OO way :)

0
 
LVL 1

Author Comment

by:mehdi
ID: 7010648
CJ,

I disagree with much of what you said about polymorphism, overloading is not necessarily to do with interfaces at all.. Its a far simpler kitty..

I like your example, its a slightly nicer way of doing things.. There was a little error though - you missed .length out from the arguments :

if(setPerson.arguments.length>0) { ...

This is the best suggestion so far - im gonna give it a bit of time to see if anyone knows how to overload without programatic intervention.

"You cannot use true polymorphism as you can in object oriented languages." - i think you are right.


Thanks,

Mehdi
0
 
LVL 22

Expert Comment

by:CJ_S
ID: 7010690
a little mistake yea :-/ not tested either :-/

Polymorphism IS the calling of a function using one and the same interface. My explanation was correct, the interpretation might be wrong.

CJ
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 33

Expert Comment

by:knightEknight
ID: 7010917
In javascript there is no actual overloading of methods, but you can mimick different method calls like this:

function setPerson(name,age)
{
   if ( name == undefined  &&  age == undefined )
      alert("setPerson() called");
   if ( age == undefined )
      alert("setPerson(name) called");
   else
      alert("setPerson(name,age) called");
}

0
 
LVL 33

Expert Comment

by:knightEknight
ID: 7010919
oops, left out an "else"
0
 
LVL 1

Expert Comment

by:Astroman
ID: 7010933
> Alfa..

> person.prototype.setPerson = setPerson; is my preferred > way of declaring a method thats all.

> Im not interested in writing one method and testing for > inputs at the moment, i'd like to be convinced
> that nobody knows how to do this the OO way :)


This is more efficient too, because the function is stored in the prototype, whereas doing the:

function person () { //define class - must declare each property of this object.
   this.name       = '';
   this.surname    = '';
   this.age        = '';
   this.setPerson  = new function(X) {setPerson(X);}
   return this;
}

method creates a copy of the function for every instantiated object.

AlphaNoMore:
"/* person.prototype.setPerson = setPerson; */ // what's this doing? Person is not an object yet?"

Most JavaScript implementations attach a prototype object to every function, in case it used as a constructor ( you can force this by creating an object and then discarding it). Properties of the prototype appear in all objects created using it, You can even add properties to a prototype at run time, which can then be seen by all the instantiated objects.


As far as I know, variadic functions are the only way to achieve polymorphic behaviour in JavaScript.
0
 
LVL 1

Author Comment

by:mehdi
ID: 7011011
Its looking unanimous,

points go to CJ guys,

CJ, The way you originaly spoke of "objects implementing interfaces" threw me off completely (implementing an interface to me means something distincly different to writing an overloading method..)

- sounded like you were talking about Danish blue cheese or something :p

Thanks all, my suspitions have been confirmed.

M
0
 
LVL 1

Author Comment

by:mehdi
ID: 7011015
not quite what i had in mind, but this seems to be as close as JavaScript comes.

0
 
LVL 22

Expert Comment

by:CJ_S
ID: 7011028
:-) I'm sorry, but that talk kind of came from VB where interfaces are actual keywords... and interfaces have a meaning to me. Exactly that.

I am sorry that you did not find a totally satisfying answer though...

CJ
0
 
LVL 1

Author Comment

by:mehdi
ID: 7011036
Well, im from a java background.. i am familiar with interfaces.. maybe (probabaly) somewhat different to VB's dunno..

Your answer was fine - There doesnt appear to be a true blue method of doing it.. (like in java) - but then your sugestion of  setPerson.arguments was new to me, and is probably what i'll be using in future - not what i call overloading - but a good answer.

-Med
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now