繁体   English   中英

如何获得函数名称?

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

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

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

而且我有一个方法返回有关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 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.

但是它返回的是I am BotI am Racebot

我怎样才能做到这一点?

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

这是因为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