Javascript 如何获取函数的名称?

Javascript 如何获取函数的名称?,javascript,function,inheritance,Javascript,Function,Inheritance,如何获取函数的名称?例如,我有一个函数: function Bot(name, speed, x, y) { this.name = name; this.speed = speed; this.x = x; this.y = y; } function Racebot(name, speed, x, y) { Bot.call(this, name, speed, x, y); } Racebot.prototype = Object.create(

如何获取函数的名称?例如,我有一个函数:

function Bot(name, speed, x, y) {
    this.name = name;
    this.speed = speed;
    this.x = x;
    this.y = y;
}
function Racebot(name, speed, x, y) {
    Bot.call(this, name, speed, x, y);
}

Racebot.prototype = Object.create(Bot.prototype);
Racebot.prototype.constructor = Racebot;
let Zoom = new Racebot('Lightning', 2, 0, 1);
console.log(Zoom.showPosition());
我有一个方法可以返回有关Bot的信息:

Bot.prototype.showPosition = function () {
    return `I am ${Bot.name} ${this.name}. I am located at ${this.x}:${this.y}`; //I am Bot 'Betty'. I am located at -2:5.
}
因此,我有一个继承Bot函数的函数:

function Bot(name, speed, x, y) {
    this.name = name;
    this.speed = speed;
    this.x = x;
    this.y = y;
}
function Racebot(name, speed, x, y) {
    Bot.call(this, name, speed, x, y);
}

Racebot.prototype = Object.create(Bot.prototype);
Racebot.prototype.constructor = Racebot;
let Zoom = new Racebot('Lightning', 2, 0, 1);
console.log(Zoom.showPosition());
Zoom.showPosition应返回:

I am Racebot 'Lightning'. I am located at 0:1.
但它返回
我是机器人
而不是
我是赛车机器人


我该怎么做

在showPosition()函数中用
Bot.name
替换
this.constructor.name
时,它应该可以工作


这是因为
Bot.name
将始终返回Bot()函数的名称,而
This.constructor.name
在Racebot实例的原型上查找设置为
constructor
属性的函数名(由于
Racebot.prototype.constructor=Racebot,该函数名为“Racebot”)

您不使用ES6类有什么原因吗?在showPosition方法中将${Bot.name}替换为${this.name}您的函数显式使用值
Bot.name
,该值不能是“Bot”以外的任何值。您可以改用
this.constructor.name