I have two javascript codes which look same each other.
The first one is like below resulting 2, 101, 102 in a row.
<script>
var val = 100;
var counter = {
val : 1,
func1 : function() {
this.val += 1;
alert('func1() this.val: ' + this.val);
func2 = function() {
this.val += 1;
alert('func2() this.val: ' + this.val);
func3 = function() {
this.val += 1;
alert('func3() this.val: ' + this.val);
};
func3();
};
func2();
}
};
counter.func1();
</script>
The following code is the second one. The Result is 2,3,4
<script>
var val = 100;
var counter = function() {
val = 1;
func1 = function() {
this.val += 1;
alert('func1() this.val: ' + this.val);
func2 = function() {
this.val += 1;
alert('func2() this.val: ' + this.val);
func3 = function() {
this.val += 1;
alert('func3() this.val: ' + this.val);
};
func3();
};
func2();
};
func1();
};
counter();
</script>
Q.Just in my opinion, this difference comes from the marks : =. Is that right?
Q.Technically, is this difference related to Lexial Environment?
Q.Are those two marks supposed to have difference scope or closure ?
Q.If the above questions are not the reason, then what could be the reason?