Is it possible to get string "markHotel" in this code?
this.markHotel = this.markPrice = function() {
// get "markHotel"
};
this.markHotel();
1 Answer 1
You could use Function.prototype.bind(). Here's a simple example:
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();
It looks like you may be doing this inside a class constructor, but it's not totally clear from your example. If that's the case, make sure not to confuse the class constructor's "this" context and the "base" function's "this" context, the latter being manually bound when setting markPrice and markHotel.
Docs for bind: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Here's a pen: http://codepen.io/bsidelinger912/pen/QKLvzL
markHotelandmarkPriceindependent functions that call into your anonymous function, passing in the name.function common() { /* common code */ }and then something like (effectively)this.markHotel = function() { common(); /* more code*/ }. This can also be done withcommonaccepting callbacks or functional composition or few other ways. Whatever the case, making the function changed based on how you called it is a code smell.function makeMarkFunction(callback) { return function() {/* common code */; callback()} }and thenthis.markHotel = makeMarkFunction(function() {/* markHotel specific stuff */}). It keeps your things nice and generic, you don't need to care what calls your function. You shouldn't need to care what calls it.