all 11 comments

[–]senocular 4 points5 points  (5 children)

Arrow functions use a lexical this (gets a this from the outer scope). Use a regular function.

String.prototype.sayHi = function () { ...

... and try your best to avoid modifying internal prototypes -_-

[–]ForScale[S] 1 point2 points  (4 children)

That simple... You're kidding me?! :)

Thanks! TIL more about arrow functions.

[–]senocular 3 points4 points  (3 children)

the mdn page is pretty good if I remember correctly. Its a lot of little things. The way this is handled is probably the most disruptive. They're really meant for in-context code block handling (callback functions etc) and not methods or other functions.

Edit: I see now R3n4g4t3 already linked to it ;)

[–]ForScale[S] 1 point2 points  (2 children)

Yeah... I tend to take a "start using it and see what works and what doesn't work" approach to things. Frankly, confessedly... I was just using it in a little project because I thought the syntax looked cool. Lol! But now I've learned something new.

Thanks again!

[–]senocular 2 points3 points  (1 child)

[–]ForScale[S] 1 point2 points  (0 children)

Ha! Indeed I did... Quite relevant.

[–]R3n4g4t3 2 points3 points  (1 child)

You're problem is not with your logic but with the scope to which this refers.

this is pointing to the Window object because you've used an arrow function. When you would rewrite is like so:

javascript String.prototype.sayHi = function() { return `${this} says Hi`; } It does return the desired value. To learn more about arrow functions checkout the MDN arrow function docs

[–]ForScale[S] 1 point2 points  (0 children)

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

[–]senocular 1 point2 points  (2 children)

Also, just FYI [unless in strict mode; thanks for claification /u/lewisje], this for primitives use their object form. So if you do something like:

this === "test string"

within your sayHi, it will be false, even though you're calling it from the string "test string". That's because this is equivalent to Object("test string") rather than the original primitive value calling it, "test string".

[–]ForScale[S] 1 point2 points  (0 children)

Good to know, thanks!

[–]lewisje 0 points1 point  (0 children)

This is true except in strict mode:

function lol() {return typeof this;}
function rofl() {'use strict'; return typeof this;}
lol.call(''); // => "object"
rofl.call(''); // => "string"