473,804 Members | 3,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using the arguments object when instantiating via constructor function

Sorry, bad title. Anyway, is there a way to pass the arguments to an object
instantiated via a constructor using the arguments object and have it
expanded, so to speak, so that it doesn't appear as a single argument? I'm
sorry, this explanation is just atrocious, but I can't think of exactly how
to word it. Maybe an example...

Take for instance Function.apply. It takes 1-2 arguments, the first being
the object to use as the context, and the second being either an array or an
instance of the arguments object which are to be the arguments for the
function. I want to do something similar but I want to also basically use
the new operator so that I get back an object.

Here's a snippet of some of my code, maybe this will help:

function Singleton()
{
this.construct. apply(this, arguments);
}

Singleton.exten d(JSClass);

Singleton.insta nce = null;

Singleton.getIn stance = function()
{
if(!this.instan ce)
{
//I want to be able to combine these two lines. If I just do new
this(arguments) , then the constructor
//thinks there is only one argument; the arguments object isn't
expanded.
this.instance = new this();

this.instance.c onstruct.apply( this.instance, arguments);
}

return this.instance;
}

function Test()
{
this.construct. apply(this, arguments);
}

Test.extend(Sin gleton);

Test.getInstanc e = function()
{
return Test.supers["Singleton"].getInstance.ap ply(this,
arguments);
};

Test.prototype. name = null;

Test.prototype. construct = function()
{
switch(argument s.length)
{
case 0:
this.name = "Test";
break;
case 1:
this.name = arguments[0];
break;
}
};

Anyway, I hope that despite this rather terrible explanation I've somehow
managed to get my point across. Any help would be much appreciated.

Thanks.

Matt
Jul 20 '05 #1
9 3812
> Sorry, bad title. Anyway, is there a way to pass the arguments to an object
instantiated via a constructor using the arguments object and have it
expanded, so to speak, so that it doesn't appear as a single argument? I'm
sorry, this explanation is just atrocious, but I can't think of exactly how
to word it. Maybe an example...

Take for instance Function.apply. It takes 1-2 arguments, the first being
the object to use as the context, and the second being either an array or an
instance of the arguments object which are to be the arguments for the
function. I want to do something similar but I want to also basically use
the new operator so that I get back an object. .... Anyway, I hope that despite this rather terrible explanation I've somehow
managed to get my point across. Any help would be much appreciated.


I'm unclear on what you want to do. Can you give us a brief specification? It is
difficult to sort through your code and try to guess what its intended effect
is.

Jul 20 '05 #2
Yeah, I'm sorry, I can't think of how to say it.

Okay, you know how with the apply() method of the Function object, you could
essentially string together a function calls without knowing the arguments
actually sent to the function? Something like:

function func_1()
{
func_2.apply(ar guments);
}

function func_2(foo, bar)
{
//etc
}

....

function someFunction()
{
//blah
func_1("bleh", 5);
}

I was wondering if there was essentially a way do the same kind of thing
when creating an object via a constructor function. Something like:

function func_1()
{
//If you do this, the arguments array for the constructor function has only
one argument, and that's another
//argument array. I want this to be expanded in a similar fashion to the
apply() method.
new this(arguments) ;
}

function TestClass()
{
this.blah = arguments[0];
this.blah2 = arguments[1];
}

function func_2()
{
func_1.apply(th is, arguments);
}

function someFunction()
{
func_2("bleh", 5);
}

I still think I'm doing a horrid job explaining this, and I'm really sorry.
I just can't think of how to explain it.

Matt
Jul 20 '05 #3
Hi,

Matt Eberts wrote:
Sorry, bad title. Anyway, is there a way to pass the arguments to an object
instantiated via a constructor using the arguments object and have it
expanded, so to speak, so that it doesn't appear as a single argument? I'm
sorry, this explanation is just atrocious, but I can't think of exactly how
to word it. Maybe an example...

Take for instance Function.apply. It takes 1-2 arguments, the first being
the object to use as the context, and the second being either an array or an
instance of the arguments object which are to be the arguments for the
function. I want to do something similar but I want to also basically use
the new operator so that I get back an object.


Is this what you mean?

function CTest()
{
this.m_strArg1 = "";
if ( arguments.lengt h > 0 )
{
this.m_strArg1 = arguments[ 0 ];
}

this.m_strArg2 = "";
if ( arguments.lengt h > 1 )
{
this.m_strArg2 = arguments[ 1 ];
}
}

CTest.prototype .alert = function()
{
alert( this.m_strArg1 + "\n" + this.m_strArg2 );
}

var oTest1 = new CTest();
oTest1.alert();

var oTest2 = new CTest( "Hello" );
oTest2.alert();

var oTest3 = new CTest( "Hello", "World" );
oTest3.alert();

Laurent
--
Laurent Bugnion, GalaSoft
Webdesign, Java, javascript: http://www.galasoft-LB.ch
Private/Malaysia: http://mypage.bluewin.ch/lbugnion
Support children in Calcutta: http://www.calcutta-espoir.ch

Jul 20 '05 #4
Matt Eberts wrote:
Sorry, bad title. Anyway, is there a way to pass the arguments to an object
instantiated via a constructor using the arguments object and have it
expanded, so to speak, so that it doesn't appear as a single argument? I'm
sorry, this explanation is just atrocious, but I can't think of exactly how
to word it.


No, this is not directly possible in javascript. The new operator
invokes both the [[Construct]] and [[Call]] properties of the
constructor function following the "new" operator. So the line

var bar = new Foo.apply(thisO bject, argumentsArray)

would attempt to create a new Function.protot ype.apply object, which (in
Mozilla at least) raises an exception because apply can not be called in
isolation.

Choices of solution lie between rewriting the program with simpler
logic, adding additional logic to the constructor function - say by
testing for magic arguments or flag variables located outside the
execution context of the constructor - or creating a generalised
mechanism to effectively split [[Construct]] and [[Call]] processing in
javascript. A function to achieve the last might go:

Function.protot ype.newApply = function (constructor, argsArray)
{ function dummy(){};
dummy.prototype = constructor.pro totype;
var newObj = new dummy();
var obj = constructor.app ly(newObj, argsArray);
if(obj && typeof obj == "object")
return obj;
return newObj;
}

The [[Call]] property of the dummy inner function is invoked, of course,
but intentionally doesn't do anything. newApply would then be called as

bar = Foo.newApply( argsArray);

or even

bar = new Foo.newApply( argsArray);

(although this would create a new object that is immediately discarded).

--

Dom
Jul 20 '05 #5
Whoops!

Sorry, getting tired over here... I rewrote an earlier version of
newApply as a method of Function.protot ype and forgot to change the
first argument into the "this" object. Code example should read:

Function.protot ype.newApply = function (argsArray)
{ function dummy(){};
dummy.prototype = this.prototype;
var newObj = new dummy();
var obj = this.apply(newO bj, argsArray);
if(obj && typeof obj == "object")
return obj;
return newObj;
}

Tested in Mozilla only

--

Dom
Jul 20 '05 #6
> Yeah, I'm sorry, I can't think of how to say it.

Okay, you know how with the apply() method of the Function object, you could
essentially string together a function calls without knowing the arguments
actually sent to the function?

I was wondering if there was essentially a way do the same kind of thing
when creating an object via a constructor function. Something like:

function func_1()
{
//If you do this, the arguments array for the constructor function has only
one argument, and that's another
//argument array. I want this to be expanded in a similar fashion to the

I still think I'm doing a horrid job explaining this, and I'm really sorry.
I just can't think of how to explain it.


Are you asking if it is possible to wrap a Constructor with a function that
takes an array that will be applied to the constructor?

If so, is it

var myObj = ConstructorWrap per([array]);

If so, then trivially,

function ConstructorWrap per(a) {
return Constructor(a[0], a[1], a[2], ...);
}

But from your description, I'm not sure at all that that is what you want. If
you can't describe something, how can you ever hope to implement it correctly?

Jul 20 '05 #7
> No, this is not directly possible in javascript. The new operator
invokes both the [[Construct]] and [[Call]] properties of the
constructor function following the "new" operator. So the line

var bar = new Foo.apply(thisO bject, argumentsArray)

would attempt to create a new Function.protot ype.apply object, which (in
Mozilla at least) raises an exception because apply can not be called in
isolation.


Okay, I kind of figured that it wouldn't. Thanks for the explanation.

Matt
Jul 20 '05 #8
Whoops squared!

After getting some sleep, I realise that the idea of calling newApply as
a method of a constructor function *and* preceding the call with a new
operator will trigger the same problem it is trying to solve, which was
to work around:

The new operator determines the object value of a following
constructor before calling it and supplying a "this" value set to a new
object. In the process, the constructor necessarily loses knowledge of
the object of which it itself may be a method.

--
Dom

Jul 20 '05 #9
> Whoops squared!

After getting some sleep, I realise that the idea of calling newApply as
a method of a constructor function *and* preceding the call with a new
operator will trigger the same problem it is trying to solve, which was
to work around:

The new operator determines the object value of a following
constructor before calling it and supplying a "this" value set to a new
object. In the process, the constructor necessarily loses knowledge of
the object of which it itself may be a method.


Get some more sleep, man.

Jul 20 '05 #10

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

Similar topics

28
20348
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
4
433
by: Tony Johansson | last post by:
Hello Experts! I have this constructor for class Flight. Flight::Flight(string flight_no, Klocka dep_t, Klocka arr_t) : no(flight_no), dep(dep_t), arr(arr_t) {} Both dep and arr are objects of the Klocka class in the definition of the Flight class.
7
12041
by: hazz | last post by:
this is a repost with more concise code (well, for me) and better questions (I hope....) . given the following two classes, my intent is to use either Activator.CreateInstance or InvokeMember pass a token into the instantiated class DBPassword and return a string; ************************************** namespace DBPasswordProvider public class DBPassword {
12
2216
by: Joe | last post by:
Hello All: Do I have to use the LoadControl method of the Page to load a UserControl? I have a class which contains three methods (one public and two private). The class acts as a control server. It "serves" back the required control (either WebControl or UserControl) based on the contents of an xml file. The code in the webform places each control in a TableCell. My problem is that the control server works as far as returning the...
5
4582
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public constructors (because we do not allow developers to instantiate them directly). Because our business objects are instantiated very frequently, the idea of using reflection sounds like a performance killer (I haven't done any tests on this, but the...
41
2588
by: Telmo Costa | last post by:
Hi. I have the following code: -------------------------------------- function Tunnel() { //arguments(???); } function Sum() { var sum = 0; for (i=0; i<arguments.length; i++) sum += arguments;
14
2117
by: B Williams | last post by:
I am stuck on an assignment that uses classes and functions. I am receiving numerous errors when I try to run a test program to see if I wrote it correctly. Can someone please point me in the right direction. These are two of the error messages I am receiving. error C2660: 'Invoice::setPartNumber' : function does not take 1 arguments error C3861: 'setItemQuantity': identifier not found This is the code. Thsnks in advance
36
2734
by: Pacific Fox | last post by:
Hi all, haven't posted to this group before, but got an issue I can't work out... and hoping to get some help here ;-) I've got a base object that works fine with named arguments when called on it's own. However when I call the child object I get an error " has no properties (in firefox)." I simple test:
61
2987
by: Sanders Kaufman | last post by:
I'm wondering if I'm doing this right, as far as using another class object as a PHP class property. class my_baseclass { var $Database; var $ErrorMessage; var $TableName; var $RecordSet; function my_baseclass(){ $this->TableName = "";
0
9579
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
10577
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10332
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...
0
10077
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
9150
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
7620
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...
0
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4299
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

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.