一.this指向
(1).补充知识
length
function test(a, b, c = 1){}
test(1);
console.log(test.length);//输出2
function test(c = 1, a, b){}
test(1);
console.log(test.length);//输出0
function test(a,b,c = 1, d, e, f){}
test(1);
console.log(test.length);//依然是2
说明es6的默认值会造成length实效
function test(a, b, d, e, f){
arguments[1] = 7;
console.log(b);
}
test(1, 2, 3, 4, 5, 6)
console.log(test.length)//打印7 5形参和实参是映射的关系
function test(a, b, d, e, f, f = 1){
arguments[1] = 7;
console.log(arguments);
}
test(1, 2, 3, 4, 5, 6);
console.log(test.length);//一旦给了默认值就会造成映射失效。输出1723456,但是形参没变的
形参赋值补充
function foo({x, y = 5}){
console.log(x, y);
}
foo({}); //un 5
foo({x:1});//1 5
foo({x:1,y=2})//1 2
foo();//报错
解决报错
function foo({x, y = 5}={}){
console.log(x, y);
}
如果没有{}输出un 5
AJAX请求
function fetch(url,{body = "",method = "get"} = {})
fetch('http://www');
就应用了默认值
(2).this指向
调用栈 Ca'llstack
![](https://i-blog.csdnimg.cn/blog_migrate/925b519b4ca78020e51ba9fbf609efd0.png)
普通情况
var x = 1;
function foo(x, y = function(){x = 2; log(2)}){
var x = 3;
y();
console.log(x);
}
foo();
console.log(x);//231
特殊情况
var x = 1;
function foo(x, y = function(){x = 2; log(x)}){
x = 3;
y();
console.log(x);
}
foo();//输出2 2
this 默认绑定 win 严格模式下un
二.箭头函数
(1).基础入门
//基本形式
() => {}
//如果形参只有一个省略()
//返回值只有一个表达式可以省略{}
var f = a => a;
var f = function(a){
return a;
}
参数不是一个的情况
let f = (a, b) => a + b;
function f(a, b){
return a + b;
}
有语句则不能省略,返回值为Un 和 fn一样
let f = (a, b) => {
var a = 3;
var b = 4;
console.log(a+b);
}
log(f()) un
(2).与解构赋值来结合
const full = ({first,last} = {} ) => first +''+last;
console.log(full({first:3,last:5}))//输出3,5//输出3,5
(3).sort
var arr = [123,12,31,23,1,4,4213,3213,43];
var arr1 = arr.sort((a,b) => a - b)
即可排序
三.rest运算符
(1).收集
//将值收集为数组
var sum = (...args) =>{
log(args[0]+args[1])
}
sum(1,2)
//收集必需是最后一个参数
let fn =(a,b,c,...d) =>{}
(2).展开
//将数字展开为各个值
function foo(x, y, z){
console.log(x, y, z)
}
foo(...[1,2,3])
foo(...[1,2,3,3,4,5])//不影响
//有点类似apply
function foo(x, y, z){
console.log(x, y, z)
}
foo.apply(un,[1,2,3,4,5]);
foo.apply(null,[1,2,3,4,5]);都指向win
//特殊用法
let a = [2, 3, 4];
let b = [1,...a,5];
[1,2,3,4,5]
(3).区别
es5写法
function sortNum(){
return Array.prototype.slice.call(arguments).sort(function(a,b){
return a - b;
})
}
log(sortNum(111,222,34,,5,6,6,6,6,d));
es6写法
const sortNum = (...args) => args.sort((a,b)=> a-b)
log((function(a){}).length);//1
log((function(..a){}).length);//0
log((function(b,..a){}).length);//1
log((function(b,..a,a=0){}).length);//1 length不再准确