JavaScript -获取调用函数的名称

JavaScript - Get name by which function has been called

本文关键字:函数 调用 获取 JavaScript      更新时间:2023-09-26

是否可以在此代码中获得字符串"markHotel" ?

this.markHotel = this.markPrice = function() {
    // get "markHotel"
};
this.markHotel();

您可以使用Function.prototype.bind()。下面是一个简单的例子:

function base() {
  console.log(this.name);
  // do some other stuff using this.name or other this props...
}
var markPrice = base.bind({ name: 'markPrice' });
var markHotel = base.bind({ name: 'markHotel' });
// this will log 'markPrice'
markPrice();
// this will log 'markHotel'
markHotel();

看起来您可能在类构造函数中这样做,但从您的示例中并不完全清楚。如果是这种情况,请确保不要混淆类构造函数的"this"上下文和"base"函数的"this"上下文,后者是在设置markPrice和markHotel时手动绑定的。

Docs for bind: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

这是一支笔:http://codepen.io/bsidelinger912/pen/QKLvzL