JS中var声明与function声明两种函数声明方式的区别

Article1:

// 函数表达式(function expression) 
var h = function() {
      // h
}

// 函数声明(function declaration) 
function h() {
      // h
}

先说两者的显著区别:

第一种声明方式也就是var声明方式, 函数只有在var语句声明之后才能被调用

第二种声明方式也就是function声明方式, 函数可以在function声明之前被调用

这是因为,

对第一种情况, 函数表达式是在函数运行阶段才赋值给变量h

对第二种情况, 函数表达式是在代码运行阶段之前, 也就是代码解析阶段才赋值给标识符h

为了证明这种说法可以看下面两个例子:

对应第一种情况,

var h = function () {
      // h
}

console.log(h)
    
h = function () {
      // h1
}

console的结果是

ƒ h() {
  // h
}

因为赋值发生在代码运行阶段, 代码自上而下运行console.log(h)所在位置只能获取它之前的赋值

对应第二种情况,

function h() {
      // h
}

console.log(h)
    
function h() {
      // h1
}

console的结果是

ƒ h() {
  // h1
}

因为赋值发生在代码解析阶段, 代码运行到console.log(h)时解析早已完成, 而解析的结果是后面那个函数h, 故会打印此结果

深入:

JS声明函数的三种方式:

1. 函数表达式: 即上面第一种方式, 这种方法使用function操作符创建函数, 表达式可以存储在变量或者对象属性里. 函数表达式往往被称为

匿名函数, 因为它没有名字. 证明这一点你可以 console.log(h.name); 可以看到打印为空 ""

2. 函数声明:  即上面第二种方式, 会声明一个具名函数, 且函数能在其所在作用域的任意位置被调用, 其创建的函数为具名函数, 证明这一

点你可以 console.log(h.name); 可以看到打印为 "h". 可在后面的代码中将此函数通过函数名赋值给变量或者对象属性

3. Function()构造器: 不推荐这种用法, 容易出问题

来源:博客园

作者:PajamaCat

原文:https://www.cnblogs.com/skura23/p/7520593.html

---------------------------------------------------------------------------

Article2:

JavaScript 函数和变量声明的“提前”(hoist)行为

简单的说 如果我们使用 匿名函数

var a = {}

这种方式, 编译后变量声明a 会“被提前”了,但是他的赋值(也就是a)并不会被提前。

也就是,匿名函数只有在被调用时才被初始化。

如果使用

function a () {};

这种方式, 编译后函数声明和他的赋值都会被提前。

也就是说函数声明过程在整个程序执行之前的预处理就完成了,所以只要处于同一个作用域,就可以访问到,即使在定义之前调用它也可以。

看一个例子

function hereOrThere() { //function statement
  return 'here';
}
console.log(hereOrThere()); // alerts 'there'
function hereOrThere() {
  return 'there';
}

我们会发现alert(hereOrThere) 语句执行时会alert('there')!这里的行为其实非常出乎意料,主要原因是JavaScript 函数声明的“提前”行为,简而言之,就是Javascript允许我们在变量和函数被声明之前使用它们,而第二个定义覆盖了第一种定义。换句话说,上述代码编译之后相当于

function hereOrThere() { //function statement
 return 'here';
}
function hereOrThere() {//申明前置了,但因为这里的申明和赋值在一起,所以一起前置
 return 'there';
}
console.log(hereOrThere()); // alerts 'there'

我们期待的行为

var hereOrThere = function () { // function expression
  return 'here';
};
console.log(hereOrThere()); // alerts 'here'
hereOrThere = function () {
  return 'there';
};

这段程序编译之后相当于:

var hereOrThere;//申明前置了
hereOrThere = function() { // function expression
 return 'here';
};
console.log(hereOrThere()); // alerts 'here'
hereOrThere = function() {
 return 'there';
};

总结

以上所述是小编给大家介绍的JavaScript 中定义函数用 var foo = function () {} 和 function foo()区别介绍,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

来源:脚本之家

作者:归去来兮-不如去兮

原文:https://www.jb51.net/article/135701.htm

---------------------------------------------------------------------------

原文地址:https://www.cnblogs.com/ryelqy/p/10723029.html