1

The reason I want to do this is kind of complicated, but long story short, you can do window[myString]=function hello(){}. Is there a way to do var hello=function [myString](){}?


The reason I want to do this is because I am creating a class generator in javascript. The problem is, I can only name the variable that I assign the constructor to, I can't actually name the class itself. So if instantiate a bunch of instances of my generated class, chrome dev tools doesn't know what the instance is, so it calls the object (anonymous function) instead of its class name. This really grinds my gears.

Here's an example of what I'm trying to do. Copy and paste into Chrome's dev tools:

function Person(name){this.name=name;};
Person.initChildClass=function(className,talkMethod){
 window[className]=function(){Person.apply(this,arguments)}
 window[className].prototype.talk=talkMethod;
}
Person.initChildClass("PoliceMan",function(){alert("I am a police man")});
Person.initChildClass("LittleBoy",function(){alert("googoogaagaa");});
var cop=new PoliceMan("Bob");
cop;

Copy and paste my code into the dev tools (Chrome) and you will see that it says window.(anonymous function) rather than "Cop" for the cop. How do I make it say "Cop"?

asked Nov 8, 2014 at 1:17
3
  • "Is there a way to do var hello=function [myString](){}?" - Well you could use eval()... Commented Nov 8, 2014 at 1:28
  • Could probably do something with a string and eval(). Commented Nov 8, 2014 at 1:28
  • Nothing promising here unfortunately: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 8, 2014 at 1:30

1 Answer 1

1

Try

func.displayName = "whatever";

but it may not work in all browsers. See Function.displayName : and same thing in Chromium

answered Nov 8, 2014 at 1:30
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks...it seems like none of the browsers (chrome, firefox, or safari) use displayName as the class name. Firefox and Safari just say Object (I'm guessing they don't put the class name there at all) and chrome still says window.(anonymous function). Judging by that link, it's still something they are sorting out.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.