函数多种类型

第一种:

function fun(n,m) {
    return n+m;
}
let return1 = fun(10,20)
let return2 = fun(100,200)
console.log(return1);
console.log(return2);

第二种,函数声明


let return1 = fun(100,200)
console.log(return1);

function fun(n,m) {
    return n+m;
}

第三种:匿名函数,也叫回调函数,将匿名函数作为参数传递给另外一个函数或方法。

setInterval(function(){
    console.log("hello");
},1000)
// 还可以写成这样
function fun(){
    console.log("hello")
}
setInterval(fun,1000)

第四种:函数表达式

const fun =function(n,m){
    return n + m;
}
let result = fun(10,22);
console.log(result);

第五种:

立即执行函数 ,代码封装
 (function(){
    let a = 10;
     let b = 20;
     console.log(a + b);
 })()

第六种:

let str= "hello";
function fun1(){
    let str = "word";
    let num = 10;
    function fun2() {
    console.log(str);
    console.log(num);
    }
    fun2();
}
fun1 ();
console.log(str);

第七种:闭包函数代码封装

const module= (
    function(){
        let a = 10;
        let b = 20;
        function add(){
            return a+b;
        }
        return add;
    }) ()

第八种:箭头函数:

箭头函数

const add= (x) => {

    return x * x;

}

在次简化

const add = x => x * x ;

原来
const fun = function (x) {
    return x * x;
}
let result = fun(2);
console.log(result);

用箭头函数简写成:

const fun =  (x) => {
    return x * x;
}
let result = fun(2);
console.log(result);

更简洁:

const fun =  x=> {
    return x * x;
}
let result = fun(2);
console.log(result);

最最最简:

const fun =  x=>  x * x;
let result = fun(2);
console.log(result);

箭头函数还有个this指向比较重要:

原:
const cat = {
    name :"miaomiao",
    sangnn(){
        let self = this;
        window.setInterval(function(){
            console.log(self.name);
        },1000)
    }
}
cat.sangnn();
用箭头后:

const cat = {
    name :"miaomiao",
    sangnn(){
        setInterval(() => {
            console.log(this.name);
        },1000)
    }
}
cat.sangnn();
箭头函数和普通函数的this指向不同,普通函数是指向调用该函数的对象。
箭头函数是在哪里定义就在那里指向谁。








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值