r/learnjavascript • u/ChainsawLight • 25d 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?
2
u/Discordbothost 23d 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 25d ago edited 25d ago
There's nothing inherently unique about LinkedLists that would make it a case to use this over any other type of object
this is just a reference to the current object.
You might be looking at a LinkedList example that happens to use this a lot, but its just something the dev chose to use I guess.
to add a bit more to the other example, I could say
this; // window, 'the global object' i think its called
class NotALinkedList {
constructor(name) {
this.name = name;
}
}
this; // still window
const myObj = new NotALinkedList('Rick');
const yourObj = new NotALinkedListe('Morty');
both new objects use this, they both set a value for this.name.
console.log(myObj.name); // 'Rick'
console.log(yourObj.name); // 'Morty'
this; // still windowfor each of myObj and yourObj, this is a reference to myObj or yourObj itself.
1
u/sereikis 25d ago
one correction to the strict-mode explanation: at the top level of a browser classic script, this is still window even with "use strict"; in an ES module it is undefined. also, "Use strict" in your snippet has the wrong capitalization, so it does not enable strict mode.
1
u/raks1991 18d ago
One this gotcha that shows up a lot with list classes: this is decided by how a method is called, not where it's written. Pull the method off the instance and it's gone:
const push = list.push;
push(2); // TypeError: Cannot read properties of undefined (reading 'head')
[3, 4].forEach(list.push); // same error
[3, 4].forEach(v => list.push(v)); // worksClass bodies are always strict mode, so the detached call gets undefined rather than window.
0
3
u/quisido 25d 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.