BubikolRamios
01-17-2009, 08:21 AM
function Car()
{
alert('car');
}
car = new Car();
the red part is what I want to alert out, but not as string constant, it should be something like
alert(this.name);
how to do that ?
Philip M
01-17-2009, 12: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
}
Car()
</script>
"The only function of economic forecasting is to make astrology look respectable". - J.K.Galbraith
mrhoo
01-17-2009, 03:31 PM
firefox and chrome will return the name from a constructor's name property-
var c1=new Car;
alert(c1.constructor.name)
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
alert(classof(/\w/g));
BubikolRamios
01-17-2009, 05:06 PM
Nope, didn't make typo want to get the red part as it is(small caps)
function Car()
{
alert('car');
}
car = new Car();
as faras I know the only way to do it is:
car = new Car('car');
function Car(derivateName)
{
alert(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 ?