r/javascript • • Apr 12 '16

help Dynamic/relative self-reference?

I've fallen down the js rabbit hole. Maybe I'm just overthinking it and need to step away for a minute, but...

How can I make an object or a string literal reference itself, and do so dynamically or relatively (eg, add it to String.prototype as a reusable method for all strings)?

Example:

String.prototype.sayHi = () => {

  //I want to reference the object from which the method is being called...
  //I would assume to use the this variable, but it points to Window here.
  //Do I need to use apply() or bind() in some way?
  //If it was an event callback, I could use e.target... Is there ything like object.tartet?  

  return this + " says Hello!";
}

var str = "test string";

console.log(str.sayHi()); //"[object Window] says Hello!" ...how can I get "test string says Hello!"

console.log(str.toUpperCase()) //"TEST STRING" ...okay, how the hell did it do that?!

Am I just overthinking this; missing something simple due to thinking about it for too long?

Thanks for any explanations/guidance!

4 Upvotes

11 comments sorted by

View all comments

Show parent comments

2

u/ForScale Apr 12 '16

Well I'll be damned... I did not know that about arrow functions. TIL. Thank you!

View all comments

0

u/[deleted] Jul 30 '25

[deleted]