第一种:
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指向不同,普通函数是指向调用该函数的对象。
箭头函数是在哪里定义就在那里指向谁。