es6 不打算从头学,遇到了就学一下:
- 函数的简写:
es5的写法:
<script>
//函数
//函数声明 两种方式
//1
function name() {
}
//2 函数表达式
var fun = function () {
};
//调用
fun();
//多形参问题
function add(a,b) {
console.log(a+b);
return a+b;
}
add(1,2);
add(1,2,3);//结果3 取前两个
add(1);//结果undefined 另一个形参得到的undefined
//返回 如果没有return 返回的是undefined;
</script>
es6箭头函数:
//函数名 = ( 参数 ) => { 方法体 }
const fun2 = (a, b) => {
console.log(a + b);
}
fun2(1, 2);
一个参数可省()
//一个参数
// const fun3 = (a) => {
// console.log(a + a);
// }
//简写
const fun3 = a => {
console.log(a + a);
}
fun3(2);
代码块只有一行时{} return 可省
const fun4 = (a,b)=>a+b;
const fun5 = (a,b)=>console(loga+b);//undefined
注意this指向不同,
箭头函数没有自己的this对象,内部的this就是定义时上层作用域中的this
const obj = {
aaa() {
setTimeout(function() {
console.log(this); //window
})
},
bb() {
setTimeout(() => {
console.log(this); //obj
})
}
}
obj.aaa();
obj.bb();
回调函数:
一个函数被作为参数传递给另一个函数(在这里我们把另一个函数叫做“otherFunction”),
回调函数在otherFunction中被调用。 可以是匿名函数也可以是命名函数