Function Scope

JavaScript’s function scope means that all variables declared within a function are visi-
ble throughout the body of the function. Curiously, this means that variables are even
visible before they are declared. This feature of JavaScript is informally known as hoist-
ing: JavaScript code behaves as if all variable declarations in a function (but not any
associated assignments) are “hoisted” to the top of the function. Consider the following
code:

var scope = "global";
function f() {
console.log(scope); // Prints "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined everywhere
console.log(scope); // Prints "local"
}

 

You might think that the first line of the function would print “global”, because the
var statement declaring the local variable has not yet been executed. Because of the
rules of function scope, however, this is not what happens. The local variable is defined
throughout the body of the function, which means the global variable by the same name
is hidden throughout the function. Although the local variable is defined throughout,
it is not actually initialized until the var statement is executed. Thus, the function above
is equivalent to the following, in which the variable declaration is “hoisted” to the top
and the variable initialization is left where it is:

function f() {
var scope; //Local variable is declared at the top of the function
console.log(scope);//It exists here, but still has "undefined" value
scope = "local";//Now we initialize it and give it a value
console.log(scope);//And here it has the value we expect
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值