gpt4 book ai didi

javascript - 我对 javascript 中变量的范围感到困惑

转载 作者:行者123 更新时间:2023-12-03 05:50:13 26 4
gpt4 key购买 nike

我正在练习 Javascript,所以我写道:

 function f(){ 
console.log(this);
var b=2;
console.log(b);
this.b++;
console.log(b);
b++;
}
f();
console.log(b);

结果令我惊讶:

/*the console result*/
window
2
2
NaN

在我看来,this 指向f();bf(); 的私有(private)变量。 this.b++b++ 对同一变量进行操作。

/*the right anwser in my mind*/
f
2
4
TypeError

请解释为什么我没有得到预期的结果。

最佳答案

让我们分解一下这里发生的事情:

function f(){
/*
Since you called this function directly, "this" is pointing
to the window object of the browser because it is the global scope
*/
console.log(this); // window
var b=2; // Assigning 2 to a local variable "b"
console.log(b); // 2 - because you are logging your local scoped variable

/*
This is really saying window.b++ and since b isn't typically
defined on the window object it is essentially saying:
window.b = undefined + 1
*/
this.b++;
console.log(b); // 2 - because you are logging your local scoped variable that hasn't changed
b++; // Increment your local scoped variable
}

f(); // Calling the function you just defined in the global scope

/*
This is actually logging window.b which is considered to be
NaN (not a number) because you incremented "undefined" and
since undefined is not a number it can't be incremented
*/
console.log(b);

关于javascript - 我对 javascript 中变量的范围感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40187620/

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