473,748 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Are multiple "constructo rs" allowed in JavaScript?

I have a question: I was wondering if it is possible to simulate the
multiple constructors, like in Java (yes, I know that the languages are
completely different)?

Let's say that I have a class called "Point" which would have two
values "x" and "y".

Now, let's say if it were the Java version, I would want two
constructors: one that accept two numbers, the other accepts a string:

public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(String coord) {
this.x = coord.charAt(0) ;
this.y = coord.charAt(1) ;
}
...
}
In JavaScript, so far I have

Point = function() {
var x;
var y;
...
}

Is it possible to have two declarations for the Point.prototype .init?
Is it even possible to have multiple constructors in JavaScript?

Thanks for the help, Andy

Dec 8 '06 #1
7 16570
VK

andrewfse...@gm ail.com wrote:
I have a question: I was wondering if it is possible to simulate the
multiple constructors, like in Java (yes, I know that the languages are
completely different)?

Let's say that I have a class called "Point" which would have two
values "x" and "y".

Now, let's say if it were the Java version, I would want two
constructors: one that accept two numbers, the other accepts a string:

public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(String coord) {
this.x = coord.charAt(0) ;
this.y = coord.charAt(1) ;
}
...
}
In JavaScript, so far I have

Point = function() {
var x;
var y;
...
}

Is it possible to have two declarations for the Point.prototype .init?
Is it even possible to have multiple constructors in JavaScript?
What you want shall be called "polymorphi c function-constructor". As
you properly noticed, a polymorphic constructor (in any language) is in
fact two or more constructors "hidden" under one common interface
(explicit in JavaScript or implicit in Java). The rest gets simple:

<script type="text/javascript">
function Point() {
switch (typeof arguments[0]) {
case 'number' : Point.$int.appl y(this, arguments); break;
case 'string' : Point.$str.appl y(this, arguments); break;
case 'object' : Point.$obj.appl y(this, arguments); break;
default : /*NOP*/
}
}

Point.$int = function(x, y) {
this.x = x;
this.y = y;
};

Point.$str = function(coord) {
this.x = parseInt(coord. charAt(0), 10);
this.y = parseInt(coord. charAt(0), 10);
}

Point.$obj = function(obj) {
this.x = obj.x;
this.y = obj.y;
}

var p1 = new Point(2,2);
var p2 = new Point('22');
var p3 = new Point({x:2, y:2});

alert(p1.x); alert(p1 instanceof Point);
alert(p2.x); alert(p2 instanceof Point);
alert(p3.x); alert(p3 instanceof Point);
</script>

Needless to say that the arguments check for validity has to be added;
also "coord.char At" is good only for a quick'n'durty demo (or if
guaranteed 0-9 coords range).

Dec 8 '06 #2
VK,
Thank you very much for your response. Very helpful.
also "coord.char At" is good only for a quick'n'durty demo (or if
guaranteed 0-9 coords range).
And yes, the string-construct was just a quick-and-dirty sample to get
the point across on this post; it will be much fuller...

Dec 9 '06 #3
VK wrote:
andrewfse...@gm ail.com wrote:
>I have a question: I was wondering if it is possible to
simulate the multiple constructors, like in Java (yes,
I know that the languages are completely different)?

Let's say that I have a class called "Point" which would
have two values "x" and "y".

Now, let's say if it were the Java version, I would want
two constructors: one that accept two numbers, the other
accepts a string:

public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(String coord) {
this.x = coord.charAt(0) ;
this.y = coord.charAt(1) ;
}
...
}
In JavaScript, so far I have

Point = function() {
That may as well be:-

function Point() {

- as that function declaration will have precisely the same result as
the assignment of a function expression to an undeclared Identifier, but
the function object will be created sooner (during variable
instantiation for the global execution context, and it will not be
possible to delete the - Point - property of the global object (though
it is extremely unlikely that anyone would attempt that anyway).

I would also be expecting to see declared formal parameters. Javascript
doesn't care about the type of arguments passed to any of its functions,
or whether all or any arguments are passed at all (defaulting unused
parameters to undefined id they are not used).
> var x;
var y;
...
}

Is it possible to have two declarations for the
Point.prototyp e.init? Is it even possible to have
multiple constructors in JavaScript?

What you want shall be called "polymorphi c function-constructor".
As you properly noticed, a polymorphic constructor (in any
language) is in fact two or more constructors "hidden" under
one common interface (explicit in JavaScript or implicit in
Java). The rest gets simple:

<script type="text/javascript">
function Point() {
switch (typeof arguments[0]) {
case 'number' : Point.$int.appl y(this, arguments); break;
case 'string' : Point.$str.appl y(this, arguments); break;
case 'object' : Point.$obj.appl y(this, arguments); break;
default : /*NOP*/
}
}

Point.$int = function(x, y) {
this.x = x;
this.y = y;
};

Point.$str = function(coord) {
this.x = parseInt(coord. charAt(0), 10);
this.y = parseInt(coord. charAt(0), 10);
}

Point.$obj = function(obj) {
this.x = obj.x;
this.y = obj.y;
}
Yet another pig's ear of an implementation from the VK school of never
understanding javascript well enough to do what is natural in the
language. In javascript you would naturally write such an object as:-

function Point(a, b){
switch(typeof a){
case 'number':
this.set(a, b);
break;
case 'string':
this.setWithStr ing(a);
break;
case 'object':
this.setWithPoi nt(a);
break;
default:
break;
}
}
Point.prototype .x = NaN; //or some other default value like zero.
Point.prototype .y = NaN;

Point.prototype .set = function(x, y){
this.x = x;
this.y = y;
};

Point.prototype .setWithString = function(coord) {
this.x = Number(coord.ch arAt(0));
this.y = Number(coord.ch arAt(1));
};

Point.prototype .setWithPoint = function(point) {
this.x = point.x;
this.y = point.y;
};

- and so avoid having ragged and useless methods (could never be used as
methods of the constructor function object) hanging off the constructor
function, avoid the unnecessary dependency on -
Function.protot ype.apply -(which designs out compatibility with JScript
versions prior to 5.6 at a stroke, for no real reason), avoids the
overheads in using - Function.protot ype.apply -, and provides the -
Point - object instances with a group of 'setter' methods that may be
useful in modifying/updating/transforming those objects.

So that is: smaller, faster, clearer, cleaner, more widely compatible
and resulting in an object with more useful features.
var p1 = new Point(2,2);
var p2 = new Point('22');
var p3 = new Point({x:2, y:2});

alert(p1.x); alert(p1 instanceof Point);
alert(p2.x); alert(p2 instanceof Point);
alert(p3.x); alert(p3 instanceof Point);
</script>

Needless to say that the arguments check for validity has to
be added; also "coord.char At" is good only for a
quick'n'durty demo (or if guaranteed 0-9 coords range).
It might still have been an idea not to use index zero with - charAt -
to set both - x - and - y - coordinates.

Richard.
Dec 9 '06 #4
In article <11************ *********@f1g20 00cwa.googlegro ups.com>,
an**********@gm ail.com writes
>I have a question: I was wondering if it is possible to simulate the
multiple constructors, like in Java (yes, I know that the languages are
completely different)?
<snip>

There's nothing wrong with having several constructors with different
names for the same 'class' of objects, provided their prototype
properties are given the same value and new objects are given the right
properties. The advantage is that each constructor is cleaner. You don't
have to test the number and type of the parameters (that's not very OO,
is it).

There's nothing new or strange about this. It's the way Borland's Turbo
Pascal did it.

John
--
John Harris
Dec 9 '06 #5
VK
Richard Cornford wrote:
function Point(a, b){
switch(typeof a){
case 'number':
this.set(a, b);
break;
case 'string':
this.setWithStr ing(a);
break;
case 'object':
this.setWithPoi nt(a);
break;
default:
break;
}
}
Point.prototype .x = NaN; //or some other default value like zero.
Point.prototype .y = NaN;

Point.prototype .set = function(x, y){
this.x = x;
this.y = y;
};

Point.prototype .setWithString = function(coord) {
this.x = Number(coord.ch arAt(0));
this.y = Number(coord.ch arAt(1));
};

Point.prototype .setWithPoint = function(point) {
this.x = point.x;
this.y = point.y;
};
That is another viable approach. What I don't like in it (doesn't mean
others have to share my feelings) - is that "obfuscates " the
inheritance chain.
Polymorphism is a horizontal process: from the entry point it goes
left, right or straight depending on arguments. Inheritance is a
vertical process (from parent to parent). This way I don't see useful
to enforce "vertical onto horizontal". As the result each Point
instance is getting a full set of sub-constructors from its constructor
with future possible fanny actions like:
var p = new Point(2, 2);
var foo = new p.set(22, 22);
// foo has nothing to do with Point if anyone wonders.

So it's a bit like gluing on each newly born chicken the leftovers of
its egg - IMHO.

Full disclosure: that's a historical moment when I do agree with John G
Harris :-) I think that polymorphism in the programming is more of an
esthetical mannerism (see my cool vs. lame notes) rather than something
technically needed.
That is not to target to OP: please take it as an overall consideration.

Dec 9 '06 #6
VK wrote:
Richard Cornford wrote:
>function Point(a, b){
switch(typeof a){
case 'number':
this.set(a, b);
break;
case 'string':
this.setWithStr ing(a);
break;
case 'object':
this.setWithPoi nt(a);
break;
default:
break;
}
}
Point.prototyp e.x = NaN; //or some other default value like zero.
Point.prototyp e.y = NaN;

Point.prototyp e.set = function(x, y){
this.x = x;
this.y = y;
};

Point.prototyp e.setWithString = function(coord) {
this.x = Number(coord.ch arAt(0));
this.y = Number(coord.ch arAt(1));
};

Point.prototyp e.setWithPoint = function(point) {
this.x = point.x;
this.y = point.y;
};

That is another viable approach.
So that garbage you posted is justified once again by your claim that it
"works", regardless of drunkenly it staggers while doing so?
What I don't like in it (doesn't mean
others have to share my feelings)
It would be amazing (and very unfortunate for them) if anyone else did.
- is that "obfuscates " the inheritance chain.
And how do you propose it is doing that? We understand that you are only
just becoming aware of prototypes in javascript and their significance
in inheritance, but that just means that what you may perceive as
obscure reflects only your very limited comprehension of the language.
Polymorphism is a horizontal process: from the entry point
it goes left, right or straight depending on arguments.
Inheritance is a vertical process (from parent to parent).
This way I don't see useful to enforce "vertical onto
horizontal".
What you don't see is a matter of no interest, particularly as it
results in your writing irrelevancies like that.

I have written one 'class' definition with a constructor that can take a
number of types of argument. That is all, and it is precisely what you
did, except your version was not informed by an understanding of
javascript.
As the result each Point instance is getting a full
set of sub-constructors from its constructor
Rubbish. Each - Point - instance is being defined with a set of 'setter'
methods. Those methods happen to be being employed by its contractor,
but there is no reason for not doing that.

"setter" (and "getter") methods are familiar concepts in OO programming,
and the OP will certainly have no trouble relating them directly to what
he has previously seen in Java. While your ragged collection of methods
of the constructor that can only be sensibly used with the -
apply/call - methods only pile needless complexity on the subject. They
are more a source of 'obfuscation' than anything I have written.
with future possible fanny actions like:
var p = new Point(2, 2);
var foo = new p.set(22, 22);
You blithering idiot. I know that you program without any understanding
of what the code you write is actually doing, and so might do something
as stupid as using the - new - operator on a function that is referred
to by the name "set" just because you can (and it will "work", by some
very broad definition of the word), but do you really think any real
programmers (and particularly experienced OO programmers) are going to
do anything so obviously stupid?
// foo has nothing to do with Point if anyone wonders.
And - p.set - is so obviously not intended to be used as a constructor
that nobody would expect it to.
So it's a bit like gluing on each newly born chicken the
leftovers of its egg - IMHO.
It is opinions like that that justify the observation that your opinions
are universally worthless.
Full disclosure: that's a historical moment when I do agree
with John G Harris :-)
You may think you do, but it is more likely that you did not understand
him.
I think that polymorphism in the programming is more of
an esthetical mannerism (see my cool vs. lame notes) rather
than something technically needed. That is not to target
to OP: please take it as an overall consideration.
That loose aggregation of words does not say one way or the other.

Richard.
Dec 10 '06 #7
VK
What I don't like in it (doesn't mean
others have to share my feelings)
- is that "obfuscates " the inheritance chain.
And how do you propose it is doing that?
In the way it supposes - IMHO - to be: if one really made her mind to
have a polymorphic constructor then she also should provide polymorphic
setter to the instances.

It doesn't prohibit using the native prototype mechanics: it even may
add some more elegance to the code (but no more effectiveness):

<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

function Point() {
this.set.apply( this, arguments);
}

Point.prototype .set = function() {
/* Arguments check is ommited
* in this sample for simplicity
*/
if (this instanceof Point) {
switch (typeof arguments[0]) {
case 'number':
this.x = arguments[0];
this.y = arguments[1];
break;
case 'object':
this.x = arguments[0]['x'];
this.y = arguments[0]['y'];
break;
default:
throw new Error('Illegal arguments : Point.set()');
}
}
else {
throw new Error('Illegal method call : Point.set()');
}
}

var p = new Point(2, 2);
alert(p.y);

p.set(3, 3);
alert(p.y);

p.set({x:4, y:4});
alert(p.y);

try {
p.set('foo');
}
catch(e) {
alert(e.message );
}

try {
var pp = new p.set(1, 1);
}
catch(e) {
alert(e.message );
}
</script>
</head>
<body>
</body>
</html>
We understand that you are only
just becoming aware of prototypes in javascript
Funny enough it is exactly my impression about you ;-)

<http://groups.google.c om/group/comp.lang.javas cript/msg/c7abb8fdbb341f5 6>

<snip>

Dec 10 '06 #8

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

Similar topics

7
42575
by: Bennett Haselton | last post by:
Is there any way to find a string representing an object's class, which will work in Internet Explorer 6? "typeof" doesn't work -- it returns "object" for all objects: x = window.open('http://www.yahoo.com/'); alert(typeof x); And I found this page: http://www.mozilla.org/js/language/js20-2002-04/core/expressions.html
9
2368
by: Player | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all. I am in the process of teaching myself C# and I think I am doing OK. I have learnt how to how to call the right constructor of a class, if the class has more than than one cosntructor, by making sure that each constructor has a different signature. I have managed to learn that and get
10
2740
by: Pantokrator | last post by:
Hi, Is there any way to "overload" a struct? e.g. having already struct stA1 { int i_ID; int i_Type; };
5
3342
by: Frederick Gotham | last post by:
If we have a simple class such as follows: #include <string> struct MyStruct { std::string member; MyStruct(unsigned const i) {
37
3976
by: jht5945 | last post by:
For example I wrote a function: function Func() { // do something } we can call it like: var obj = new Func(); // call it as a constructor or var result = Func(); // call it as a function
10
2739
by: Angel Tsankov | last post by:
Hello! Is the following code illformed or does it yield undefined behaviour: class a {}; class b {
13
20774
by: learning | last post by:
Hi I have a static class written by other team which encapsulates a database instance. but I need to extend it to incldue other things. I know that C# static class is sealed and can;t be inherited & I don't want to copy + paste code. How can I inherit those member variables? Thanks
2
2245
by: Christof Warlich | last post by:
Hi, I'd like to define a class that should behave as much as posible like std::string, but that has some small additional property: class ExtendedString: public std::string { public: void someExtendedFunctionality(void) {} };
30
4698
by: kj | last post by:
My book (Flanagan's JavaScript: The Definitive Guide, 5th ed.) implies on page 111 that the following two constructs are equivalent: ( x.constructor == Foo ) and ( x instanceof Foo ) The author states that the instanceof operator computes its result
0
8818
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9355
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9307
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9225
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8234
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3296
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.