是否可以在这段代码中获取字符串“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 时手动绑定(bind)的。
绑定(bind)文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
关于JavaScript - 获取调用函数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232604/