JavaScript/作用域:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” |
|||
| (未显示同一用户的4个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
在 JavaScript 中,作用域分为三种:函数作用域、with 作用域、全局作用域,其中变量标识符的查找是从当前作用域开始逐级向上向外查找,直到全局作用域为止。 | |||
== 作用域链 == | == 作用域链 == | ||
=== 示例 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
(function a() { | |||
var val = 'hello'; | |||
(function b() { | |||
(function c() { | |||
val = 'world'; | |||
})(); | |||
console.log(val); | |||
})(); | |||
})(); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
world</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
(function a() { | |||
var val = 'hello'; | |||
(function b() { | |||
(function c() { | |||
window.val = 'world'; | |||
})(); | |||
console.log(val); | |||
})(); | |||
})(); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
hello</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
(function a() { | |||
var val = 'hello'; | |||
(function b() { | |||
(function c() { | |||
var val = 'world'; | |||
})(); | |||
console.log(val); | |||
})(); | |||
})(); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
hello</pre>}}}} | |||
== 示例 == | == 示例 == | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
var foo = function() { | var foo = function() { | ||
var local = {}; | var local = {}; | ||
| 第13行: | 第54行: | ||
undefined</pre>}}}} | undefined</pre>}}}} | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
var foo = function() { | var foo = function() { | ||
local = {}; | local = {}; | ||