2

I have a method inside a class that uses lodash's get and looks like this:

get(path, defaultValue = '–') {
  const result = _.get(this, path, defaultValue);
  return result;
}

Assuming that result is a string, is there a chance to add a prototype method isDefault? I've tried implementation below and it does not work:

get(path, defaultValue = '–') {
  const result = _.get(this, path, defaultValue);
  result.isDefault = () => result === defaultValue;
  return result;
}

I know that I could just wrap the result in a class and define the method there, but I also want to just write console.log(result) to get a string printed on my screen.

4
  • 1
    NB: you're specifically not adding this to the prototype (which affects every instance). You're just trying to add a method as a property of a single instance. Commented Oct 11, 2018 at 17:57
  • 1
    maybe this can give u some clues stackoverflow.com/q/6804370/6442877 Commented Oct 11, 2018 at 17:58
  • @Alnitak: Good point, but writing result.prototype.isDefault gives an error Commented Oct 11, 2018 at 18:00
  • @Ancinek that's because only Function objects (and classes) have a .prototype property. Commented Oct 11, 2018 at 19:20

1 Answer 1

1

Your string is a primitive string which is not really an instance of string, so you need to wrap your result assignment in String instance:

const result = new String(_.get(this, path, defaultValue));
Sign up to request clarification or add additional context in comments.

3 Comments

That works, but it makes result harder to use as if it were a string primitive. For example console.log(result) doesn't log a simple string anymore. You need to explicitly call result.toString().
@MarkMeyer you also can use __proto__ assignment but I'd not recommend to do this as it is a bad practice: result.__proto__.func = function() { ... };
I'm going to accept it as it works the way I expected it to work. Maybe someone can give a deeper insight about this solution - I'm going to have a small research on this tomorrow.

Your Answer

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.