【发布时间】: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