View Full Version : new object name

01-17-2009, 09:21 AM
function Car()

car = new Car();

the red part is what I want to alert out, but not as string constant, it should be something like


how to do that ?

Philip M
01-17-2009, 01:57 PM
As a function name cannot be changed there is no easy way to access it.

The following is somewhat contrived (not sure if it is really what you want):-

<script type = "text/javascript">

var y = function Car() {

y = y.toString();
var len = y.length;
var z = y.substring(9,len);
var w = z.indexOf("(");
z = z.substring(0,w);
alert (z); // Car



"The only function of economic forecasting is to make astrology look respectable". - J.K.Galbraith

01-17-2009, 04:31 PM
firefox and chrome will return the name from a constructor's name property-
var c1=new Car;

Most browsers return undefined, however.

You could define a name property in each constructor,
or dedicate a method to return any object's constructor name.

function classof(what){
var tem, C= what.constructor;
tem= C? C.toString().match(/function\s+([a-zA-Z][\w\$]+)\s*\(/): '';
return tem? tem[1]: '';

//test case
function Car(specs){
var mycar= new Car();
alert('classof(mycar)='+ classof(mycar));

// it works as well for native objects

01-17-2009, 06:06 PM
Nope, didn't make typo want to get the red part as it is(small caps)

function Car()

car = new Car();

as faras I know the only way to do it is:

car = new Car('car');

function Car(derivateName)

Example of purpose of all this if it would work:

function Car()
this.publicF = function()

tmpInnerHTML = "<DIV onclick = '" + this.name + ".publicF()'"

someObj.innerHTML = tmpInnerHTML;


car = new Car();
car5 = new Car();
car100 = new Car();

any other idea ?