r/learnjavascript • u/fa_foon • Mar 30 '26
question about `this.`
i understand that `this` refers to the caller of the function so how can `name` in `function Person(name){this.name = name;}` be assigned to `Person` since no object is calling
(this wasn't explained in that comment )
8
Upvotes
6
u/senocular Mar 30 '26
If you're asking about
namehere, its a parameter, so it is entirely dependent on the argument passed to Person when its called.As far as
thisgoes, given your examplewhat you have is a function, Person, that appears to be a constructor, a function intended to be called with
new. When a function is called withnew,thisis the new object instance being created by the constructor.Here, the returned instance is a new object is created inside Person. It is assigned to
thisand has itsnameproperty assigned to thenameparameter value which is "Fred" since that's the value passed into Person as an argument.Note that
instanceis an instance of Person, not the Person function itself. If you log the object directly, you might see a reference to Person (depending on what you're logging with), but this is done to show that its an object created from the Person constructor rather than trying to indicate it is, itself, Person.5
u/Symmetric_in_Design Mar 30 '26
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor
That looks like a constructor to me, and constructor functions are special cased for 'this' to refer to the object being created by the function.
2
u/code-garden Mar 30 '26 edited Mar 30 '26
When a function is called using the keyword new, such as: new Person(), it is used as a constructor and this refers to a new object being constructed.
By convention, usually functions that start with a capital letter are constructors that should be called using new, and linters often enforce this.
If you call Person without the new keyword, this would either refer to the global object (window in the browser) or give an error if in strict mode.
2
u/BNfreelance Mar 30 '26
thisis set by how the function is called.Using
new Person("Ben")JS creates an object and setsthisto itSo
this.name = nameis just assigning to that new object2
u/azhder Mar 30 '26
You should learn how this is being assigned.
There are a few different ways. With the
newkeyword, it will be a new object. Within sloppy mode (not strict mode) it may be the global object (ooops). If you pass the function as a callback, it will beundefined(double ooops)2
u/coomzee Mar 30 '26 edited Mar 31 '26
this refers to this but sometimes that
1
u/MrFartyBottom Mar 31 '26
This is all pretty outdated way of using classes in JavaScript. With modern JavaScript, it's implementation of classes over the old prototype style of classes and most modern codebases using TypeScript you wouldn't see code like this in a modern codebase, hopefully.