JavaScript - 获取调用函数的名称

时间:2016-08-30 16:23:25

标签: javascript

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

this.markHotel = this.markPrice = function() {

    // get "markHotel"

};

this.markHotel();

1 个答案:

答案 0 :(得分:1)

您可以使用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();

看起来你可能在类构造函数中这样做了,但是你的例子并不完全清楚。如果是这种情况,请确保不要混淆类构造函数"这个"背景和"基地"功能"这个"上下文,后者在设置markPrice和markHotel时手动绑定。

绑定文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

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

相关问题