javascript - 在一个函数中,在变量之前使用/不使用 var 会发生什么?

标签 javascript

这是我的代码

var a = this.innerHTML;

var b = 'blababibbaib';

if(a !== b)
    {
        c = a;
        return this.innerHTML = b;
    }
else
    {
        return this.innerHTML = c;
    }

和var

var a = this.innerHTML;

var b = 'blababibbaib';

if(a !== b)
    {
       var c = a; // here with the var it makes c undefined :-(
        return this.innerHTML = b;
    }
else
    {
        return this.innerHTML = c;
    }

我这样做的原因是因为我想要一个 onclick 事件的函数,它会在原始事件和 var b 之间来回变化。真的只是为了好玩。

但我不明白为什么当您在 c 变量前面添加 var 时,一旦您点击它,它就会变成未定义的。有人会照亮我吗?

我猜它在函数中使用时与变量范围有关????

提前致谢:-)

编辑:

好吧,我这样做是为了用 var 声明它,但我仍然不确定为什么。

在函数之外,我在声明 c 之前添加了一个 if 检查

if(!c) var c = '';

但就像我说的,我仍然想听听发生了什么事以及为什么谢谢 :-)

编辑 2:谢谢大家,现在阅读有关提升的内容。

我觉得我很困惑,似乎你也不需要检查 c。思想可能很重要……哦,好吧。再次感谢

最佳答案

第二个例子中发生的事情等同于:

var a = this.innerHTML;

var b = 'blababibbaib';

var c; // all "var" are hoisted to the top of a function body

if(a !== b)
    {
        c = a;
        return this.innerHTML = b;
    }
else
    {
        // local c variable not set yet - undefined
        return this.innerHTML = c;
    }

显然c在这里是未定义的,因为它只有在没有设置的时候才会输出。我怀疑你真正想要的是:

var a; //This persists after the function is invoked

myelement.onclick = function () {
    if (!a) { // Only save the value if it isn't already set
        a = this.innerHTML;
    }
    var b = 'blababibbaib';

    if (this.innerHTML == b) {
        return this.innerHTML = a;
    } else {
        return this.innerHTML = b;
    }
};

可以看到here .

就第一个片段而言,它之所以有效,是因为 c 的值不是函数的本地值,并且在调用后仍然存在。当您在函数体中分配或引用一个变量而不使用 var 关键字声明它时,它会自动引用具有相同名称的 window 的属性。请考虑以下事项:

window.c = "Hello, world.";

//Note how there is no local c variable;
//the c here refers to window.c
function test1(){
    alert(c);
}

//There is a c variable local to the 
//function, so the value alerted is not the value of window.c
function test2(){
    var c;
    alert(c);
}

test1(); // alerts "Hello, world."
test2(); // alerts "undefined"

在第一个片段中,只要 HTML 不是 "blababibbaib",您就将 window.c 的值更改为 this.innerHTML .当值 "blababibbaib" 时,您依赖于 window.c 来重置元素的 innerHTML

您可能想继续阅读 hoisting在 JS 中,以及 implicit globals .

关于javascript - 在一个函数中,在变量之前使用/不使用 var 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14189495/

相关文章:

javascript - 不想在 Javascript 中打印 Array of Array

javascript - Chrome 切换到串行下载脚本

javascript - Geolocation Cordova 插件导致应用卡住/崩溃

javascript - 无法使用 Karma 运行测试

javascript - 表单验证失败但仍然提交

javascript - 滑动面板动画

javascript - 类型 'subtle' 上不存在属性 'typeof webcrypto'

javascript - CSS - 如何制作光标 : pointer when hover a parent which is an another component in ReactJS?

javascript - 相同的产品但在表中添加另一行(仅限 JavaScript)

javascript - 我可以修改或扩展 ChartJS 吗?