3

Is it possible to get string "markHotel" in this code?

this.markHotel = this.markPrice = function() {
 // get "markHotel"
};
this.markHotel();
asked Aug 30, 2016 at 16:23
10
  • stackoverflow.com/questions/2648293/… Commented Aug 30, 2016 at 16:25
  • @RobM. The issue here is that the function itself is anonymous and has no name. I'm not sure you can do what the OP is asking here. Commented Aug 30, 2016 at 16:26
  • 2
    If you really need to do this (it looks a bit smelly - is this an XY Problem?), you could make markHotel and markPrice independent functions that call into your anonymous function, passing in the name. Commented Aug 30, 2016 at 16:30
  • 1
    @holden321 then it is an XY problem. You don't want to get what was called you just need common code. You can have something like function common() { /* common code */ } and then something like (effectively) this.markHotel = function() { common(); /* more code*/ }. This can also be done with common accepting 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. Commented Aug 30, 2016 at 16:37
  • 1
    function makeMarkFunction(callback) { return function() {/* common code */; callback()} } and then this.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. Commented Aug 30, 2016 at 16:50

1 Answer 1

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

answered Aug 30, 2016 at 16:36
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.