gpt4 book ai didi

javascript - JS引擎如何操作未声明的变量?

转载 作者:行者123 更新时间:2023-11-29 21:12:31 24 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<head>
<meta lan="en-us" charset="UTF-8">
</head>
<body>

<p>Counting with a local variable.</p>

<p id="demo"></p>
<button type="button" onclick="myFunction('+')">Count +</button>
<button type="button" onclick="myFunction('-')">Count -</button>

<script>
document.getElementById("demo").innerHTML = 0;
function add(number){
var counter = 0;
return function() {return counter += number;}
}
function sub(number){
var counter = 0;
return function() {return counter -= number;}
}

var counterIncr = add(1);
var counterDicr = sub(1);

function myFunction(s){
if( s == "+"){
/*this.*/counter1 = counterIncr();
}
else if (s == "-"){
/*this.*/counter2 = counterDicr();
}

if(!counter2 && counter1){
document.getElementById("demo").innerHTML = counter1;
}
else if(!counter1 && counter2){
document.getElementById("demo").innerHTML = counter2;
}
else if(counter1 && counter2){
document.getElementById("demo").innerHTML = (counter1 + counter2);
}
}
</script>

</body>
</html>

在研究 JS 闭包期间,我扩展了一个 W3C 示例,实现了一个带有两个按钮的 HTML 页面。该示例只有一个按钮。第一个按钮增加点击计数器,第二个按钮减少该计数器。定义了一个函数“myFunction”,它使用两个变量“counter1”和“counter2”来完成这项工作。这些变量被声明为 this.counter1 和 this.counter2,并且此页面的实现按预期工作。我的问题:当我从 counter1 和 counter2 声明中省略“this”时(...只是为了好玩)我的页面仍然有效(当然不是在严格模式下)但只有当两个按钮都被单击一次时。如何解释这种行为,或者 JS 引擎如何在幕后操作(处理)未声明的变量?

最佳答案

未显式声明的变量将始终自动成为全局变量:

function myFunction() {
// explicitly declared variable (local)
var explitic = "foo";

// implicitly declared variable (global)
implicit = "bar";
}

myFunction(); // call function

console.log(typeof explicit); // prints "undefined" since local
console.log(typeof implicit); // prints "string" since global

更多例子here .

另一方面,严格模式根本不接受隐式声明的变量:

"use strict";

var explicitGlobal = "foo";

function myFunction() {
// works because explicitGlobal is already defined
explicitGlobal = "foo2";

// Uncaught ReferenceError: implicit is not defined
implicit = "bar";
}

myFunction();

关于javascript - JS引擎如何操作未声明的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com