简体   繁体   中英

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.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:

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:

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

But it returns I am Bot not I am Racebot .

How can I do that?

When you replace this.constructor.name with Bot.name in your showPosition() function it should work.

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)

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