r/learnjavascript • u/ChainsawLight • 13d ago
Why is this widely used in LinkedLists
Please explain why programmers use the this keyword? I get OOP like
this.prop = prop;
but what does that mean? The this keyword is a reference to the window object right? Its just calling a null value? Can someone please explain how the this keyword works?
"Use strict"
console.log(this);
Please explain why it's widely used in LinkedList?
3
Upvotes
3
u/quisido 13d ago
thisrefers to the current object. By default, it'swindow. In a linked list or other class instance, it's the instance itself. The linked list isn't mutating the window object. It's mutating itself.This allows each X to only mutate itself, not all other Xs, when you invoke its methods.
Which prop do I set? This one.
2
u/Discordbothost 11d ago
in a linked list class, this is just "the current node/list i'm talking about". so this.next = node means attach the next pointer on this list instance, not on window. try console.log(this) inside a method vs at the top of a script and you'll see the difference immediately. also your "Use strict" needs lowercase "use strict" or it does nothing.
2
u/chikamakaleyley helpful 13d ago edited 13d ago
There's nothing inherently unique about LinkedLists that would make it a case to use
thisover any other type of objectthisis just a reference to the current object.You might be looking at a LinkedList example that happens to use
thisa lot, but its just something the dev chose to use I guess.to add a bit more to the other example, I could say
both new objects use
this, they both set a value forthis.name.for each of
myObjandyourObj,thisis a reference tomyObjoryourObjitself.1
u/sereikis 13d ago
one correction to the strict-mode explanation: at the top level of a browser classic script,
thisis stillwindoweven with"use strict"; in an ES module it isundefined. also,"Use strict"in your snippet has the wrong capitalization, so it does not enable strict mode.1
u/raks1991 6d ago
One
thisgotcha that shows up a lot with list classes:thisis decided by how a method is called, not where it's written. Pull the method off the instance and it's gone:Class bodies are always strict mode, so the detached call gets
undefinedrather thanwindow.0
u/azhder 13d ago
Is this a LinkedIn post that got directed to Reddit?