Im having in big trouble | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Im having in big trouble

I'm not able to understand why it is written this.name = name & this.age = age ?? This is the js code function person (name, age) { this.name = name; this.age = age; } var John = new person("John", 25); var James = new person("James", 21); document.write(John.age);

22nd Oct 2017, 11:01 PM
Faisal Khan
Faisal Khan - avatar
4 Answers
+ 5
The key is: 'name' and 'this.name' doesn't refer to the same variable... 'name' is a variable identifier auto-declared as argument of the 'person' object constructor function. 'this.name' is a property of the 'this' object, creating a new scope context when constructor is called with the 'new' keyword. 'name' is local (private) to the constructor function scope, while 'this' properties are accessible from outside of each object instances.
23rd Oct 2017, 1:56 PM
visph
visph - avatar
+ 4
So there is a function called person that takes in a name and a age. when you make a variable called John, then assign it to a the function "person", it takes a name and a age. Now, John is on his own, him and James do not share the common age and age is not a global variable. Because John needs a unique age, you use the " this " key word.
22nd Oct 2017, 11:24 PM
Dillion Piazza
Dillion  Piazza - avatar
+ 2
Could you please provide the full code?
22nd Oct 2017, 11:20 PM
Dillion Piazza
Dillion  Piazza - avatar
0
Question uploaded
22nd Oct 2017, 11:22 PM
Faisal Khan
Faisal Khan - avatar