【问题标题】:How can I get the name of a function?如何获取函数的名称?
【发布时间】:2018-10-03 14:44:11
【问题描述】:

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

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 Bot 而不是 I am Racebot

我该怎么做?

【问题讨论】:

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

标签: javascript function inheritance


【解决方案1】:

当您在 showPosition() 函数中将 this.constructor.name 替换为 Bot.name 时,它应该可以工作。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2011-10-26
    • 2023-03-17
    • 2016-06-13
    相关资源
    最近更新 更多