javascript高级知识分析——定义函数

代码信息来自于http://ejohn.org/apps/learn/。

可以使用哪些方式来声明函数?

function isNimble(){ return true; } 
var canFly = function(){ return true; }; 
window.isDeadly = function(){ return true; }; 
console.log(isNimble, canFly, isDeadly);//function isNimble() function canFly() function window.isDeadly()

在这段代码用,我们用了三种方式声明全局函数:

1.isNimble,用的是命名函数。

2.canFly,声明一个匿名函数,把这个函数分配给一个全局变量(用var)。根据函数的本质,可以使用canFly()调用。

3.isDeadly,声明一个匿名函数,把这个函数分配给window对象的属性isDeadly,可以使用window.isDeadly()和Deadly()调用这个函数。

函数声明的顺序是否重要?

var canFly = function(){ return true; }; 
window.isDeadly = function(){ return true; }; 
console.log( isNimble() && canFly() && isDeadly()); //true
function isNimble(){ return true; }

当使用命名函数声明时,函数在当前作用域都可以引用。

在哪里分配引用才可以被引用?

console.log( typeof canFly == "undefined","不可以引用" ); 
console.log( typeof isDeadly == "undefined", "也不可以" ); 
var canFly = function(){ return true; }; 
window.isDeadly = function(){ return true; };

当使用声明匿名函数再分配给变量时则不可以。

是否可以在return下面声明函数?

function stealthCheck(){ 
  console.log( stealth());//true
  return stealth(); 
  function stealth(){ return true; } 
} 
stealthCheck();

果然,使用命名声明的函数可以在当前作用域任何地方引用。

原文地址:https://www.cnblogs.com/winderby/p/4063087.html