Reputation: 79
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?
Upvotes: 2
Views: 62
Reputation:
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)
Upvotes: 3