0

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?

ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35
Jinny Song
  • 125
  • 1
  • 10

1 Answers1

0

In the first snippet, var val = 100;defines a the variable as global with a value of 100. val : 1, defines a property named val inside the counter object.

In the second snippet, val = 1; defines the assignment of the value 1 of the global varaible val.

So it is normal, that the result is different: it's a question about variable scope.

ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35