+ 2
Method question
Hello, complete newbie hwre. Why does following script return Paul 90 instead of Paul 100. Thanks! var test = 100; if (test>110); { var test = ("90"); } function person(name, age) { this.name = name; this.age = age; this.changeName = function (name) { this.name = name; } this.changeAge = function (age){ this.age=test; } } var p = new person("David", 21); p.changeName("John"); var c = new person ("Paul",23); c.changeAge("34"); document.write(p.name + "\n" + p.age + "<br>"); document.write(c.name + "\n" + c.age);
2 Antworten
+ 1
Ville Keituri
The reason was because when you made that "if" statement, you terminated it without giving it a body ,by placing a semi-colon immediately after it.
Meaning
========
if(test > 100);
{
test = ("90")
}
due to the semi-colon after "if(test > 100)", the if statement is terminated prematurely, and as such
{
test =("90");
}
is executed as a block on its own, thus "test = 90".
If you remove the semi-colon after "if(test > 100)", you'll get the desired result.
Here's a correct version of the code
https://code.sololearn.com/WZ8C29Q7zSMs/?ref=app
+ 1
Thank you for explanation!