JavaScript-获取调用函数的名称
在这段代码中可以得到字符串“markHotel”吗JavaScript-获取调用函数的名称,javascript,Javascript,在这段代码中可以得到字符串“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 o
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时被手动绑定
用于绑定的文档:
这是一支钢笔:@RobM。这里的问题是函数本身是匿名的,没有名字。我不确定你是否可以按照OP的要求来做。如果你真的需要这样做(它看起来有点臭-这是一个吗?),你可以制作
markHotel
和markPrice
独立的函数调用匿名函数,传递名字。@holden321那么这是一个XY问题。你不想得到所谓的东西,你只需要普通的代码。您可以使用类似于function common(){/*common code*/}
的内容,然后使用类似于(有效地)this.markHotel=function(){common();/*more code*/}
的内容。这也可以通过common
接受回调、函数组合或其他几种方式来实现。无论如何,根据调用方式更改函数都是一种代码味道。function makeMarkFunction(callback){return function(){/*common code*/;callback()}
然后this.markHotel=makeMarkFunction(function(){/*markHotel-specific stuff*/})
。它使您的东西保持良好和通用性,您不需要关心什么调用了您的函数。你不必在意它叫什么。