匿名函数具名化

110 阅读1分钟
/* 
 * 匿名函数“具名化”:建议/标准 
 *   + 自执行函数
 *   + 函数表达式 
 *     const fn=function fn(){};
 *     document.body.onclick=function bodyClick(){};
 *     Array.prototype.unique=function unique(){};
 *     ...
 *   + 回调函数
 *   + ...
 */

1、

// "use strict";
(function (x) {
    // ...
    // 在JS严格模式下不支持
    console.log(arguments.callee); //函数本身「只能在函数内部使用」
    console.log(arguments.callee.caller); //函数执行所在的上下文对应的函数
})(10); 

2、

function fn() {
console.log(arguments.callee.caller); //=>b函数「就是在自己上下文中执行的,返回null」
}
function b() {
    fn();
}
b();

3、

(function fn(x) {
    // ...
    // console.log(fn); //函数本身,这样就可以在函数内部使用了
    fn();
})(10);
// console.log(fn); //=>Uncaught ReferenceError: fn is not defined 匿名函数具名化和实名函数不是一个概念「具名化的名字不能再函数以外使用」 

4、

5、

6、

7、