简体   繁体   English

如何获得函数名称?

[英]How can I get the name of a function?

How can I get the name of a function? 如何获得函数名称? For example, I have a function: 例如,我有一个函数:

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

and I have a method which returns info about Bot: 而且我有一个方法返回有关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.
}

So then i have a function which inherits the Bot function: 因此,我有了一个继承Bot函数的函数:

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 should return: Zoom.showPosition应该返回:

I am Racebot 'Lightning'. I am located at 0:1.

But it returns I am Bot not I am Racebot . 但是它返回的是I am BotI am Racebot

How can I do that? 我怎样才能做到这一点?

When you replace this.constructor.name with Bot.name in your showPosition() function it should work. 在showPosition()函数中用Bot.name替换this.constructor.name ,它应该可以工作。

This is because Bot.name will always return the name of your Bot() function, whereas this.constructor.name looks up the name of the function set as constructor property on the prototype of your Racebot instance (which is "Racebot" due to Racebot.prototype.constructor = Racebot) 这是因为Bot.name将始终返回您的Bot()函数的名称,而this.constructor.name在Racebot实例的原型上查找设置为constructor属性的函数的名称(由于“ Racebot” Racebot.prototype.constructor = Racebot)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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