简体   繁体   中英

Is there a way to dynamically give an anonymous function a name in javascript?

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"?

Try

func.displayName = "whatever";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM