js创建函数的几种方式

函数声明:

这个是最普通的声明函数方法

  function total(num1, num2) {
    return num1 + num2
  }
  console.log(total(2, 3));//5

函数表达式( 函数字面量)

这个是将函数直接赋值给变量

let a= function total(num1, num2) {
    return num1 + num2
  }
  console.log(a(2, 3));//5

方法对象类

作用:净化命名空间,防止全局变量污染

  var a={
    total:function(num1,num2){
      return  num1+num2
    },
    reduce: function (num1, num2) {
      return num1 * num2
    },
  }
  console.log(a.reduce(2,8));//16
  console.log(a.total(2,5));//7

也可以给单个属性添加方法:

 let b = function () {
       console.log('原函数');
  }
  b.reduce = function (num1, num2) {
    return num1 * num2
  }
 console.log(b.reduce(2,4));//8


b()//原函数

函数名(   )  -----这个代表是执行这个函数

函数名       -----这个没有扩号,则代表函数的本身

匿名函数

匿名函数是指函数没有名字            匿名函数属于函数表达式

function (){..............}

 这个是最简单的匿名函数

(function ( ){alert(1)})( )

(function ( ) { alert(1) }( ))

这个函数声明完了,马上进行调用,只能使用一次(也叫自执行函数)

函数跟变量一样存在函数提升

 console.log(a);
   function a() {

  }

函数声明与变量声明先后顺序

函数声明会优于变量的声明,也就是说函数会提升到变量的前面

console.log(a);//a的函数体
    var a = 2;
   function a() {
    return  1
   }
  console.log(a);//2

解析 

 var a =function(){}    
 console.log(a);//function a() {}
  a=2        //被重新赋值
console.log(a);//2

 

posted @ 2022-06-21 11:07  长安·念  阅读(307)  评论(0)    收藏  举报