What is "this"?

Nobody knows!

Because JavaScript is weird

  • 1
    Aside from C#, Java and PHP also using this concept, this is the context your fucking function is called in. If you don't know about arrow functions, just let js be.

    I know you were joking but reading "what is blue? Nobody knows what color the color blue is. Js is so fucked up!!1!?1" for the 200000th time is kind of boring by now.
  • 1
    @nitwhiz Yeah but there's confusing things like

    var abc = {
    crack: "cocaine",
    drug: this.crack

    This is just where it starts though. It can get so much more fucky.
  • 3
    @AlgoRythm why is this confusing?
    In this assingnment your context is the abc object.
  • 6
    @nitwhiz Case and point, it's actually the enclosing scope, not the abc object. This would refer to Window if this code is in the global scope
  • 4
    @nitwhiz love how you came barging in and proved @AlgoRythm s point for him. +1 nicely done.
  • 2
    @nitwhiz You are probably the only person I've seen defending the stupid shit in JavaScript
  • 1
    @AlgoRythm @grumpyoldaf well that wasn't really my brightest moment.:D

    Guess you guys got a point. But to put it in perspective anyway, you wouldn't do stuff like that in c# or java without expecting it to be the enclosing scope.
  • 1
    @nitwhiz My point was, that "this" in JS can be a bit weird/confusing, compared to C# and Java.

    Thanks @AlgoRythm for backing me up with a great argument!
  • 1
    @TangChr but what @AlgoRythm wrote is evaluated the same in js, java and c#. The only exception being the compile time error.

    Am I being a total dingus again or am I seeing this wrong?
  • 2
    @nitwhiz I can’t speak for Java. But a similar example in C#, the this would be the object it is contained in. Period. It does not change based on execution context or enclosing scope, as opposed to JS.

    And if you really wanna dig in more, I recommend Kyle Simpson’s “You don’t know JS” and the section on this. There s some weird shit going on with JS when it comes to the this keyword. Made me go WTF the first time I read it.
  • 1
    @nitwhiz C# and JS objects work quite differently. You can construct an object from anything, on the fly, in JS. In C#, afaik, any object must be a class of some sort. What I didn't isn't possible in c#. And if you did it in c#, by defining a class ABC, and in the constructor, did the equivalent (for example):

    crack = "cocaine";
    drug = this.crack;

    Then "this" would, in fact, refer to the instance of ABC class. This is what makes my first JavaScript example so fucky to think about.
  • 2
    @grumpyoldaf @AlgoRythm @TangChr well then I'm very sorry that I was so cocky in the first place. Never ran into these weird fuckeries since ES6.
  • 1
    @nitwhiz oh you have nothing to feel sorry about. Feel lucky you didn’t find out how this works in prod like I did. That’s a rant for another day!
Add Comment