zoukankan      html  css  js  c++  java
  • ES6基础-6

    函数

        //函数默认参数使不允许由同名参数
        function fn(name,name,age){
            //同名后边参数覆盖前面的
            console.log(name,name);
        }
        fn("webcyh",21);
        function test(name,age=21){
            console.log(name,age);
        }
        //当传递的参数不为空或者undefined则有效果
        test("webcyh",undefined);
        test("webcyh",null);
        //不定参数
        function test2(name,...values){
            console.log(name);
            //不定参数返回的是数组
            console.log(values);
        }
        test2("webcyh",1,2,2,2,2,2);
        //箭头函数 自执行 当箭头函数没有参数或者参数多个的时候需要括号
        //当函数只有一条语句且有返回值 可以不需要花括号
        //当返回值为对象 需要添加()
        (()=>console.log("hello"))();
    
        var f = v=>v;
    
        console.log(f(1));
        //箭头函数 没有 this、super、arguments 和 new.target 绑定。
        //this指向在外边的this 而且不能作为构造函数 不能使用new
        console.log((()=>({name:"webcyh",age:21}))());
        function test3(){
            setInterval(()=>{
                console.log(this.a);
            },1000);
        };
        test3.call({a:"webcyh"});

    在这里this指向外边的this好处

     this 对象一直很令人头大,回调函数,经常看到 var self = this 这样的代码,为了将外部 this 传递到回调函数中,那么有了箭头函数,就不需要这样做了,直接使用 this 就行

    const test = {
            age:21,
            getAge:()=>console.log(this.age)
        }
        const test1 = {
            age:21,
            getAge(){
                console.log(this.age);
            }
        }
        var age = 1;
        test.getAge();
        test1.getAge();
        //注意在监听点击事件的时候可能导致无法绑定到相应的元素上面

    迭代器

    //迭代器lterator 这是一种新的遍历机制
        //有两个核心概念
        //迭代器是一个统一的接口方便数据结构被便捷访问
        //用于变量数据结构元素的指针
        var str = "hello world!";
        var t = str[Symbol.iterator]();
        console.log(t.next());
        console.log(t.next());
        console.log(t.next());//t.next()返回一个对象,里边done为false说明还没遍历完
        for(let t of str){
            console.log(t);
        }
        
        //可迭代的类型有 set map 数组 字符串 和 dom元素 但是普通的Object对象无法进行迭代输出 类数组对象无法直接迭代需要转换成普通的数组
         var obj = {length:2,0:"webcyh",1:21};
        // for(let item of obj){
        //     console.log(item);
        // }
        //以上会报错
        for(let item of Array.from(obj)){
            console.log(item);
        }
        //let 和var
        for(var i1 of [1,2,3]){
    
        }
        console.log(i1);
        for(let i2 of [1,2,3]){//使用let  const 每次迭代均为创建一个存储空间 均能保证迭代在内部作用域
        }
        console.log(i2);

  • 相关阅读:
    linux 里 /etc/passwd 、/etc/shadow和/etc/group 文件内容解释
    IIS 7.5 配置 php 5.4.22 链接 sql 2008(用PDO链接数据库)
    如何学好一本编程语言
    从零开始学YII2.0
    android AlertDialog 错误 OnClickListener 报错
    胖哥从零开始做一个APP系列文章的通知
    引用自定义控件出现的问题
    java hashMap实现原理
    粗略读完opengl
    求知若饥,虚心若愚
  • 原文地址:https://www.cnblogs.com/webcyh/p/11459682.html
Copyright © 2011-2022 走看看