JavaScript函数扩展与箭头函数超详细讲解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript函数扩展与箭头函数超详细讲解

亦世凡华、   2022-11-09 我要评论

函数参数扩展

ES6 允许给函数参数赋初始值:

形参初始值 具有默认值的参数,一般位置要靠后(潜规则);使用参数默认值时,函数不能有同名参数;参数默认值不是传值的,而是每次都重新计算默认值表达式的值。

function add(a,b,c=10){
    return a + b + c; 
}
let result = add(1,2);
console.log(result); // 13

与解构赋值结合,如果传递数值了就用传递的数值,否则就用默认值

function connect({host="127.0.0.1",username,password,port}){
    console.log(host);
    console.log(username);
    console.log(password);
    console.log(port);
}
connect({
    // host:'localhost', //传了值就用这个,如果没有传就用默认值
    username:'root',
    password:'root',
    port:80
})

当函数传参给予了默认值,length属性将忽略传递默认值的长度。

<script>
    function fun(a,b,c){
        console.log(fun.length);
    }
    fun()//3
    function fun(a,b,c=1){
        console.log(fun.length);
    }
    fun()//2
</script>

当我们给参数设置默认值时,会自动形成作用域,仅限函数内部的数据传值,如果函数形参没有传递数值,就会找函数之外的数,以下面例子为例:

<script>
    var x = 1;
    // 函数形参定义了x的值,就不需要去外面再找x值
    function f(x, y = x) {
        console.log(y);
    }
    f(2) // 2
    var a = 1;
    // 函数形参没有定义a的值,所以需要去外面找a的值,所以打印为1
    function g(b = a){
        let a = 2;
        console.log(b);
    }
    g()//1
</script>

rest参数

ES6引入rest参数(其形式为:...变量名),用于获取函数的多余参数,这样就不需要使用arguments对象,rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。

<script>
    // ES5 获取实参的方式
    function date(){
        console.log(arguments);
    }
    date(1,2,3,4,5)
    console.log('--------------');
    // rest参数
    function date1(...args){
        console.log(args);
    }
    date1(1,2,3,4,5)
</script>

箭头函数

在ES6中规定允许使用箭头 ( => ) 定义函数。

//正常写法
let fn = function(){
}
//箭头函数
let fn1 = (a,b) =>{
    return a + b;
}
console.log(fn1(1,2)); //3

箭头函数的使用规范

箭头函数中:this 是静态的,this始终指向函数声明时所在作用域下的 this 的值。

function getName(){
    console.log(this.name);
}
let getName2 = () =>{
    console.log(this.name);
}
// 设置 window 对象的 name 属性
window.name = '张三'
const person = {
    name:'小张'
}
// 直接调用
getName() //张三
getName2() //张三
//call 方法调用
getName.call(person) //小张
getName2.call(person) //张三 箭头函数是静态的,始终指向开始时的第一个值

箭头函数中: 不能构造实例化对象,否则会报错。

let Person = (name,age) =>{
    this.name = name;
    this.age = age;
}
let p = new Person('张三',18)
console.log(p);

箭头函数中:不能使用 arguments 变量。

let fun = () => {
    console.log(agruments);
}
fun(1,2,3)

箭头函数中:箭头函数的简写方式。

1、省略小括号,当形参有且只有一个的时候。

let add = n => {
    return n*n;
}
console.log(add(8));//64

2、 省略花括号,当代码体只有一条语句时,此时 return 必须省略,而且语句的执行结果就是函数的返回值。

let pow = (n) => n+n;
console.log(pow(2)); //4

箭头函数的嵌套

箭头函数内部,还可以使用箭头函数:

<script>
    // ES5 语法的多重嵌套
    function insert(value) {
    return {into: function (array) {
        return {after: function (afterValue) {
        array.splice(array.indexOf(afterValue) + 1, 0, value);
        return array;
        }};
    }};
    }
    console.log(insert(2).into([1, 3]).after(1)); //[1, 2, 3]
    // ES6 箭头函数嵌套
    let insert = (value) => ({into: (array) => ({after: (afterValue) => {
        array.splice(array.indexOf(afterValue) + 1, 0, value);
        return array;
    }})});
    console.log(insert(2).into([1, 3]).after(1)); //[1, 2, 3]
</script>

箭头函数案例

点击 div 2s 之后颜色变成 pink :

<head>
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            background: #58a;
        }
    </style>
</head>
<body>
    <div id="id"></div>
    <script>
        // 获取元素
        let div = document.querySelector('#id')
        // 绑定事件
        div.addEventListener("click",function(){
            // 如果想用 this 调用,先在外部保存this,否则this会指向window对象
            let _this = this;
            // 点击 2s 之后让盒子颜色改变
            setTimeout(()=>{
                // div.style.background = 'pink'
                _this.style.background = 'pink'
            },2000)
        })
    </script>
</body>

从数组中返回偶数的元素:

<script>
    const arr = [1,6,9,10,100,25];
    /* filter() 方法创建一个新的数组,函数中有return返回值。
     * 若返回值为true,这个元素保存到新数组中;
     * 若返回值为false,则该元素不保存到新数组中;原数组不发生改变。
    */
    const result = arr.filter(function(item){
        if(item%2===0){
            return true;
        }else{
            return false
        }
    })
    console.log(result);
    console.log('-------------------');
    const result1 = arr.filter(item => item % 2 ===0 )
    console.log(result1);
    // 箭头函数适合与 this 无关的回调:定时器。数组方法的回调
    // 箭头函数不适合与 this 有关的回调:事件回调、对象的方法 
</script>

使用总结:

箭头函数没有自己的this对象

不可以当做构造函数,即不能对箭头函数使用new命令,否则报错

不可以使用arguments对象,该对象在函数体内不存在,如需使用用rest函数代替

不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们