Function Expressions scope

本文探讨了JScript中函数表达式与声明在不同浏览器中的表现差异,尤其是在作用域可见性和递归调用方面的行为。通过具体示例展示了IE、Firefox、Opera和Safari等浏览器如何处理带有名称标识符的函数表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*
官网原文:
In JScript the identifier in a function expression is visible in the enclosing scope because such expressions are treated as function declarations. Example:
*/
<script>
var foo = function bar(b)
{
if (b == true)
{
bar(); // works because bar is visible inside itself

}
else
{
document.write("hello");
}
}
foo();
// works because foo is a ref to Function object bar(false);
// should fail because bar is not visible here
</script>
/* Output:
IE: prints "hellohello"
FF: prints “hello” followed by syntax error (bar is not defined)
Opera: prints “hello” followed by ReferenceError (Reference to undefined variable: bar)
Safari: prints “hello”
*/


/*
Note: IE treats nested function expressions containing a function name as a function declaration that is scoped to the enclosing function (applying the second bullet rule from §10.1.3 instead of case 3 of the semantics in §13. In the following example the forward reference to x gets resolved in IE, whereas we get a syntax error in FF and TypeError in Opera. Example:
*/
<script>
function f(x)
{
x();
y = function x()
{
document.write("inner called ")
};
document.write(x);
document.write(arguments[0]);
}
document.write("test 4 ");
f("param");
</script>
/*
Output:
IE: test 4 inner called function x() {document.write("inner called ")}function x() {document.write("inner called ")}
FF: test 4 Opera: test 4
Safari: test 4
Here is another example of the same issue:
*/
<script>
function foo()
{
function bar() {}
var x = function baz(z)
{
document.write("baz" + z);
if (z) baz(false);
};
x(true); // legal;
bar(); // legal
baz(true); // should be illegal, is legal
}
foo();
</script>
/* The function statement bar should add “bar” to foo‟s variable object. The function expression baz should NOT add “baz” to foo‟s variable object, but it should be in scope when baz is called, so that it can do the recursive call.
Output: IE: baztruebazfalsebaztruebazfalse
FF: baztruebazfalse (followed by an error – baz not defined)
Opera: same as FF
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值