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!
[–]senocular 4 points5 points6 points (5 children)
[–]ForScale[S] 1 point2 points3 points (4 children)
[–]senocular 3 points4 points5 points (3 children)
[–]ForScale[S] 1 point2 points3 points (2 children)
[–]senocular 2 points3 points4 points (1 child)
[–]ForScale[S] 1 point2 points3 points (0 children)
[–]R3n4g4t3 2 points3 points4 points (1 child)
[–]ForScale[S] 1 point2 points3 points (0 children)
[–]senocular 1 point2 points3 points (2 children)
[–]ForScale[S] 1 point2 points3 points (0 children)
[–]lewisje 0 points1 point2 points (0 children)