簡體   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