473,831 Members | 2,278 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An object's constructor name as a string. Can definitely be determined?

Hi,

I want to know the name of an object's constructor function as a
string. Something like this

<script type="text/javascript">
function Foo(){};
var a = new Foo();
alert('"' +
a.constructor.t oString().match (/function\s*([a-zA-Z\$][\w\$]+)[^\w\$]/)[1]
+ '"');
</script>

Although this works in IE, Opera, Firefox, Safari I'm not sure that it
is guaranteed to work.

I looked in the ECMA-262 specs about the returned string for
Function.protot ype.toString() in section 15.2.4.2. It says that the
whitespace, line terminators and semi-colon use are implementation
dependent. I think the above regular expression can handle those
difference.

What I'm worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?

Thank you,
Peter

Nov 6 '06 #1
31 3145

Peter Michaux wrote:
Hi,

I want to know the name of an object's constructor function as a
string. Something like this

<script type="text/javascript">
function Foo(){};
var a = new Foo();
alert('"' +
a.constructor.t oString().match (/function\s*([a-zA-Z\$][\w\$]+)[^\w\$]/)[1]
+ '"');
</script>
[...]
What I'm worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?
A quick test shows that you can use an anonymous function as a
constructor, and it is returned in the form of a function declaration,
but it's actually a statement:

var nameObj = function(name){
this.name = name;
this.showName = function(){aler t(this.name);}
}

var x = new nameObj('Peter' );
x.showName();
alert(x.constru ctor);

shows:

function (name) { ...}

which only makes sense as a function statement. I guess you could say
it's in the form of a declaration because the left hand side is
missing. Of course you might fix that with:

var nameObj = function nameObj (name){ ... }

But that may not be helpful. In some browsers the constructor object
has a name property, but not all unfortunately. Can I be of any less
help? :-)
--
Rob

Nov 6 '06 #2
Peter Michaux wrote:
Hi,

I want to know the name of an object's constructor function as a
string. Something like this

<script type="text/javascript">
function Foo(){};
var a = new Foo();
alert('"' +
a.constructor.t oString().match (/function\s*([a-zA-Z\$][\w\$]+)[^\w\$]/)[1]
+ '"');
</script>

Although this works in IE, Opera, Firefox, Safari I'm not sure that it
is guaranteed to work.
No, it's not. I don't like object models where it is necessary to query
instances about their types. But if you feel you must, make it reliable. The
constructor property is not reliable because it is lost in the simple
inheritance pattern:

function Bar(){}
Bar.prototype = new Foo();

var b = new Bar();
alert(b.constru ctor === Bar); // produces false

So be explicit in identifying your type names.

Foo.prototype.t ype = 'Foo';
Bar.prototype.t ype = 'Bar';

alert(a.type);
alert(b.type);

http://javascript.crockford.com/
Nov 6 '06 #3
RobG wrote:
Peter Michaux wrote:
Hi,

I want to know the name of an object's constructor function as a
string. Something like this

<script type="text/javascript">
function Foo(){};
var a = new Foo();
alert('"' +
a.constructor.t oString().match (/function\s*([a-zA-Z\$][\w\$]+)[^\w\$]/)[1]
+ '"');
</script>
[...]
What I'm worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?

A quick test shows that you can use an anonymous function as a
constructor, and it is returned in the form of a function declaration,
but it's actually a statement:

var nameObj = function(name){
this.name = name;
this.showName = function(){aler t(this.name);}
}

var x = new nameObj('Peter' );
x.showName();
alert(x.constru ctor);

shows:

function (name) { ...}

which only makes sense as a function statement. I guess you could say
it's in the form of a declaration because the left hand side is
missing. Of course you might fix that with:

var nameObj = function nameObj (name){ ... }

But that may not be helpful. In some browsers the constructor object
has a name property, but not all unfortunately. Can I be of any less
help? :-)
Hi Rob,

I tested the things you mentioned also. It seems the the return value
of toString() can take the form of a function statement when the
function is anonymous. So does this mean the ECMA specs are a little
bit wrong? If a function is anonymous, there is no way that toString
will be able to return a function declaration since the identifier is
not available.

Thanks,
Peter

Nov 6 '06 #4
VK

Peter Michaux wrote:
It seems the the return value
of toString() can take the form of a function statement when the
function is anonymous. So does this mean the ECMA specs are a little
bit wrong? If a function is anonymous, there is no way that toString
will be able to return a function declaration since the identifier is
not available.
That was already explained at
<http://groups.google.c om/group/comp.lang.javas cript/msg/81452faadf0019d 1>
- please read it carefully.

This way it shouldn't surprise you any more than
function foo() {}
var bar = foo;
alert(bar.toStr ing()) // that the name will be? foo of course

ECMAScript specs are not exactly wrong, but they are very confusingly
written: so confusingly actually that professional C++ programmers did
not get it right in application to this matter and they had to say
sorry latter (JScript team) though sorry should be ECMA's free-lancers.

In application to your routine two more issues has to be taken into
consideration:

1) var foo = function(){} creates anonymous function with toString
method returning "function(){... "
At the same time anonymous functions in event handlers (like one in
<body onload="") has toString method returning "function anonymous()
{...". The same is for function created by using Function()
constructor. It has nothing to do with some pragrammatical differences,
it was just preserved this way for legacy reasons. Brendan Eich once
had to explain it and say sorry on bugzilla.mozill a.org, later I'll
find the link again.
In any case you have to adjust the neuristic for both possible values
for anonymous functions.

2) toString method can be overloaded to prevent source code dump or to
be used for something completely else. It is rather easy fixable as
well but in such case it looks more like a reverse engineering so I
will not advise: but only point onto such possibility.

Nov 6 '06 #5

Peter Michaux wrote:
RobG wrote:
Peter Michaux wrote:
[...]
What I'm worried about is that he specs say the return value has the
form of a "function declaration". Does that mean the returned string
will definitely contain the name of the constructor function? Could it
instead return something like just "function () {}"?
A quick test shows that you can use an anonymous function as a
constructor, and it is returned in the form of a function declaration,
but it's actually a statement:
[...]
I tested the things you mentioned also. It seems the the return value
of toString() can take the form of a function statement when the
function is anonymous. So does this mean the ECMA specs are a little
bit wrong? If a function is anonymous, there is no way that toString
will be able to return a function declaration since the identifier is
not available.
I don't think the specification is wrong or contradictory, the wording
is:

"15.3.4.2 Function.protot ype.toString ( )
"An implementation-dependent representation of the function is
returned. This representation has the syntax of a
FunctionDeclara tion. Note in particular that the use and placement
of white space, line terminators, and semicolons within the
representation string is implementation-dependent."

The important part is "has the syntax of", it doesn't say "it is" a
function declaration. It is similar to the confusion caused by the
occasional use of "undefined" when "not defined" is meant.

The function is returned in a format that looks like a function
declaration, but since it's anonymous, there is no identifier or name.
The only solution to me is to put an identifier into function
statements, but that will only suit code you can control, not a general
case.

This may be an interesting exercise but using the constructor property
as the basis for program logic is unlikely to be reliable. Try
Douglas' suggestion: give your native function objects an explicit type
parameter.
--
Rob

Nov 6 '06 #6
Peter Michaux wrote:
It seems the the return value of toString() can take the form of a
function statement when the function is anonymous. ...
That is precisely the form it /should/ take.
If a function is anonymous, there is no way that toString will be
able to return a function declaration since the identifier is not
available.
You seem to be overlooking the rather important initial sentence:

An implementation-dependent representation of the function is
returned.

An implementation is free to use whatever identifier it likes. An
obvious choice is "anonymous" , though anything (including a
randomly-generated identifier) will do.

Mike
Nov 6 '06 #7
RobG wrote:
<snip>
I don't think the specification is wrong or contradictory, the wording
is:

"15.3.4.2 Function.protot ype.toString ( )
"An implementation-dependent representation of the function is
returned. This representation has the syntax of a
FunctionDeclara tion. Note in particular that the use and placement
of white space, line terminators, and semicolons within the
representation string is implementation-dependent."

The important part is "has the syntax of", it doesn't say "it is" a
function declaration. It is similar to the confusion caused by the
occasional use of "undefined" when "not defined" is meant.

The function is returned in a format that looks like a function
declaration, but since it's anonymous, there is no identifier or name.
The only solution to me is to put an identifier into function
statements, but that will only suit code you can control, not a general
case.

At the beginning of section 13 of the specs it says

Syntax

FunctionDeclara tion:
function Identifier (FormalParamete rList_opt) { FunctionBody }

FunctionExpress ion:
function Identifier_opt (FormalParamete rList_opt) {FunctionBody}

Does the following sound reasonable? In the FunctionDeclara tion the
Identifier is not optional so a function declaration cannot be
anonymous. An anonymous function is always introduced through a
FunctionExpress sion.

Perhaps the section about toString() for a function should say that the
returned value has the syntax of a FunctionExpress ion. This would
account for anonymous functions.

This may be an interesting exercise
I think that is all it has become now.

but using the constructor property
as the basis for program logic is unlikely to be reliable.
Try Douglas' suggestion: give your native function objects an explicit type
parameter.
I think this is good advice.

Thanks Rob and Douglas.

Peter

Nov 6 '06 #8
VK
FunctionDeclara tion:
function Identifier (FormalParamete rList_opt) { FunctionBody }

FunctionExpress ion:
function Identifier_opt (FormalParamete rList_opt) {FunctionBody}

Does the following sound reasonable? In the FunctionDeclara tion the
Identifier is not optional so a function declaration cannot be
anonymous. An anonymous function is always introduced through a
FunctionExpress sion.
Did you try?
<script type="text/javascript">
function() {}
</script>

That is a perfectly valid syntax: but useless program-wise.
FunctionDeclara tion is not evaluated, so there is no "hook" left to use
this function in your program. This is all what they tried (but failed)
to say.
Perhaps the section about toString() for a function should say that the
returned value has the syntax of a FunctionExpress ion. This would
account for anonymous functions.
They couldn't say it in 1999, because already there was a great amount
of scripts using toString value from anonymous functions defined for
intrinsic handlers (see again my other post in this thread). I do agree
in advance that the chosen form for them:
"function anonymous() {..." is sub-optimal and semi-contadictory (if
function is called "anonymous" then it is called somehow and so it is
not anonymous). More logical would be do not use the word "anonymous"
at all as in the latter practice or at least use another order:
"anonymous function(){..."

But whatever was done - it was done, and we have to deal now with the
legacy outcomes.

Nov 7 '06 #9
VK wrote:
<snip>
Did you try?
<script type="text/javascript">
function() {}
</script>

That is a perfectly valid syntax:
No it is not. No ExpressionState ment may commence with the 'function'
keyword and the Identifier in a Function Declaration is not optional.
but useless program-wise. FunctionDeclara tion is not evaluated,
so there is no "hook" left to use this function in your program.
This is all what they tried (but failed) to say.
<snip>

Who are these "they" and why are they trying to be so incoherent?

Richard.

Nov 7 '06 #10

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

Similar topics

28
20357
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.
2
2986
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the Intel compiler it has stopped working. I think the singleton pattern static instance thing may be at the root of the problem, but I'm not sure. I had to add calls to instance() in regCreateFn, which gets the behaviour more in line with what I was...
1
3978
by: Bo Xu | last post by:
Object of Combination By Bo Xu Introduction A combination of n things, taken s at a time, often referred as an s-combination out of n, is a way to select a subset of size s from a given set of size n. There are n!/(s!(n-s)!) ways to do this. Donald E. Knuth gives several methods (algorithms) to generate all the s-combinations in . In such procedure-oriented way, each s-combination is processed while it's being generated. In some
15
1931
by: Sam Kong | last post by:
Hello! I got recently intrigued with JavaScript's prototype-based object-orientation. However, I still don't understand the mechanism clearly. What's the difference between the following two? (1)
16
2909
by: anonymous.user0 | last post by:
The way I understand it, if I have an object Listener that has registered as a listener for some event Event that's produced by an object Emitter, as long as Emitter is still allocated Listener will stay alive. Is this correct? If this is correct, I've got a problem. Let's say I've got an object Customer that has an PurchaseList (Collection) of Purchase objects. Now, these Purchase objects were pulled from a datasource Datasource. The...
8
2027
by: a | last post by:
I'm trying to save data from a custom object into the profile object, but it is not structured the way that I want. I'm trying to get the custom object to serialize as xml to a Profile object like so: <Teachers> <Teacher> <Classes> <Class>
0
1840
by: a | last post by:
I need to create an instance of a custom object 'School.Teacher' and use it in a Profile object. I'm developing a bad case of "Pretzel Logic" thinking about this. Filling the custom object 'School.Teacher' as an ArrayList creates the proper information (see aspx code below), but I'm unable to use this ArrayList in the Profile object. The aspx code below shows the attempt and error message.
7
3586
by: Steve | last post by:
I am building an object library for tables in a database. What is the best practice for creating objects like this? For example, say I have the following tables in my database: User: - Id - FirstName - LastName - CompanyId (many-to-one )
275
12472
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9794
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10778
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
10496
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
10538
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
9319
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
7750
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
6951
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
5622
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3967
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.