【JS】JavaScript语句和声明之function

253 阅读3分钟

函数定义的方式有三种:

  • 构造函数的形式

可以将要封装的代码以字符串的形式传递给Function构造函数。

var 函数名 = new Function("代码语句...");

不过,在实际开发中,很少使用构造函数的形式来创建一个函数对象。

  • 函数声明的形式
function 函数名([形参1,形参2...形参N]){
    语句...
}

函数声明定义一个具有指定参数的函数。此篇主要讲函数声明形式创建函数有关内容。

  • 函数表达式的形式
var 函数名 = function ([形参1,形参2...形参N]){
    语句...
};

下面就讲讲函数声明形式定义一个函数相关内容。

1.描述

函数声明创建的函数是一个 Function 对象,具有 Function 对象的所有属性、方法和行为。

函数可以被有条件来声明,也就是说函数声明可能出现在一个 if 语句里。有的浏览器会将这种有条件的声明看成是无条件的声明,即是无论条件是true还是false,浏览器都会创建函数。因此,它们不应该被使用

默认情况下,函数的返回值是 undefined。如果想返回一个其他值,函数必须通过一个return 语句指定返回值。

2.有条件的创建函数

根据上述描述部分内容我们知道函数声明可能在if语句里,但,这种 声明方式在不同的浏览器里可能有不同的效果。因此,不应该在生成环境代码中使用这种声明方式,应该使用函数表达式来代替

var hoisted = "fun" in this;
console.log(`"fun" name ${hoisted ? "is" : "is not"} hoisted. typeof fun is ${typeof fun}`);
if (false) {
  function fun(){
     return 1; 
  }
}

输出结果如下:

  • 在Chrome浏览器中:
"fun" name is hoisted. typeof fun is undefined

fun 变量名被提升,但是 typeof funundefined.

  • 在Firefox浏览器中:
"fun" name is hoisted. typeof fun is undefined

fun 变量名被提升,但是 typeof funundefined.

  • 在Edge浏览器中:
"fun" name is not hoisted. typeof fun is undefined

fun 变量名未被提升,且 typeof funundefined.

  • 在Safari浏览器中:
"fun" name is hoisted . typeof fun is function

fun 变量名被提升,且 typeof funfunction.

注意:即便上述代码中if(false)改为if(true),结果都是一样的。代码如下:

var hoisted = "fun" in this;
console.log(`'fun' name ${hoisted ? "is" : "is not"} hoisted. typeof fun is ${typeof fun}`);
if (true) {
  function fun(){
     return 1; 
  }
}

输出结果如下:

  • 在Chrome浏览器中:
"fun" name is hoisted. typeof fun is undefined

fun 变量名被提升,但是 typeof funundefined.

  • 在Firefox浏览器中:
"fun" name is hoisted. typeof fun is undefined

fun 变量名被提升,但是 typeof funundefined.

  • 在Edge浏览器中:
"fun" name is not hoisted. typeof fun is undefined

fun 变量名未被提升,且 typeof funundefined.

  • 在Safari浏览器中:
"fun" name is hoisted . typeof fun is function

fun 变量名被提升,且 typeof funfunction.

3.栗子

  • 声明函数 下面代码声明了一个函数,该函数返回了两个数值的和,参数是加数a和加数b.
function add(a,b){
  return a + b ;
}
  • 调用函数 封装到函数中的代码不会立即执行,函数中的代码会在函数调用的时候执行

语法: 函数对象();

当调用函数时,函数中封装的代码才会被执行。

function add(a,b){
  return a + b ;
}
add(1,3);  //返回值为4

最后

如果发现内容有误,欢迎评论指出错误,感谢ing!