命名函数表达式

时间:2022-06-14
本文章向大家介绍命名函数表达式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

好文章,可惜中文译文已经无法访问了。不过在cssrain上找到一篇:www.cssrain.cn/demo/named%20function%20expression/Named%20function%20expressions%20demystified.htm

英文地址还在:kangax.github.com/nfe/

看IE6、IE7、IE8与其它非IE下的不同

 var f = function foo(){
    return typeof foo; // "foo" is available in this inner scope
  };
  // `foo` is never visible "outside"
  typeof foo; // "undefined"
  f(); // "function"

除IE6、7、8外,其它浏览器均显示foo为undefined

这是JScript的bugs,好像IE9的beta2中已经修复了?(尚未安装过,有待证实)

IE中有两个“特性”

1、函数声明中的标识符允许包含.运算符,例如

function window.onload() {}

2、函数表达式中的标识符可以被函数外部访问

var f = function g(){}; 
typeof g; // "function"
具名函数表达式,果真是篇好文章:

《Named function expressions demystified》

每周读一篇,思路更清晰^_^。

看完这些资料,做玉伯这道题应该就很简单了吧?

f = function() { return true; };
g = function() { return false; };

(function() {
    if (g() && [] == ![]) {
        f = function f() { return false; };
        function g() { return true; }
    }
})();

alert(f()); // true or false ?

我的答案是,在IE6、7、8下面,代码等价于:

<script type="text/javascript">
f = function() { return true; };
g = function() { return false; };


(function() {
	var f, g;

	 g = function() {return true;}
	 f = function() {return false;}

	if (g()) {
		f = f;
    }
})();

alert(f());
</script>

在FF下的代码等价于:

  <script type="text/javascript">
f = function() { return true; };
g = function() { return false; };


(function() {
	
	if (g()) {
        /**..*/
    }
})();

alert(f());
</script>

在Chrome下等价于:

<script type="text/javascript">
f = function() { return true; };
g = function() { return false; };


(function() {
	var g;

	function g() {
		return true;
	}

	if (g()) {	
	
       f = function f() {
			return false;
	   }

    }
})();

alert(f()); 
</script>

那么就来测试一下不同浏览器下的效果吧 ~ ~

<script type="text/javascript"> f = function() { return true; }; g = function() { return false; }; (function() { if (g() && [] == ![]) { alert(f); f = function f() { return false; }; function g() { return true; } } })(); alert(f()); // true or false ? </script>预览代码