0

VARIABLE behaviour NOT understood, anyone please explain, code inside Script Tag is as follows.

MyStudentClass = { name : "Ramesh", age : 10, school : "BalMandir", rollno : 11, EnterDetailFunction: function() { rollno = prompt ("Enter your roll number here : "); }, DisplayDetailFunction: function() { alert ("Entered roll number was : "+rollno); } }; MyStudentClass.EnterDetailFunction(); MyStudentClass.DisplayDetailFunction(); document.write(MyStudentClass.rollno);

20th Oct 2020, 6:57 AM
mohan borkar
mohan borkar - avatar
3 odpowiedzi
+ 5
The result of your code snippet is that, the DisplayDetailFunction() alerts the input value, but the MyStudentClass.rollno prints 11 to the document, that's because 1. MyStudentClass.rollno is a property of the object MyStudentClass, with a value of 11, as assigned in line 6 of your code bit. 2. rollno inside EnterDetailFunction() is adding a new property to the scope the function is being called - global scope, which is window.rollno 3. rollno inside DisplayDetailFunction is same as point 2 above - window.rollno That's the input value is alerted, but 11 is printed to document. Read the bottommost part - undeclaredVarInScope : https://code.sololearn.com/WwhKQUoMbXHH/?ref=app Further readings about Closures, a very important concept in JavaScript : https://www.sololearn.com/post/91113/?ref=app
20th Oct 2020, 7:24 AM
Gordon
Gordon - avatar
+ 3
use `this.rollno` not `rollno` in methods. without `this` the variable name refers to l̶o̶c̶a̶l̶ global variable which is implicitly declared (without using var or let). This will fail in strict mode. plus, follow js naming conventions. methods and variables should be named in lower camelCase not upper CamelCase. Note that `MyStudentClass` is an object, not a class and you are also missing let/var/const before it. --- Edited after Gordon's answer (which is correct) : assigning a variable without var/let/const adds it to global scope not to scope of function where it's declared.
20th Oct 2020, 7:07 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
O.K. variable with same name "rollno" has two different storage locations due to two different scopes.
20th Oct 2020, 1:37 PM
mohan borkar
mohan borkar - avatar