简体   繁体   English

:和=与javascript函数之间的区别

[英]Difference Between : and = with javascript function

I have two javascript codes which look same each other. 我有两个看起来彼此相同的JavaScript代码。

The first one is like below resulting 2, 101, 102 in a row. 第一个类似下面的结果,即连续2、101、102。

<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 结果是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? 问:如果以上问题不是原因,那么可能是什么原因?

In the first snippet, var val = 100; 在第一个代码段中, var val = 100; defines a the variable as global with a value of 100 . 将变量定义为global,其值为100 val : 1, defines a property named val inside the counter object. val : 1,counter对象内部定义了一个名为val的属性。

In the second snippet, val = 1; 在第二个片段中, val = 1; defines the assignment of the value 1 of the global varaible val . 定义全局变量val的值1的分配。

So it is normal, that the result is different: it's a question about variable scope . 因此,结果是不同的是正常的:这是关于variable scope的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM