zoukankan      html  css  js  c++  java
  • 【分享】ES5 & ES6 基础

    一、什么是ES5

      附上一览表

      (5.1中文 (2011.6)): http://lzw.me/pages/ecmascript/

      (5.1英文PDF):http://www.ecma-international.org/ecma-262/5.1/ECMA-262.pdf

      ECMAScript 5 浏览器支持情况如下图:

      作为ECMAScript第五个版本,增加特性如下。

      1. 严格模式(strict mode)

        严格模式,'use strict';  

        限制了一些用法,使JS变得更为严谨;

        严格模式下,未使用var定义的全局变量会报错;

        IE10+开始支持。

      2. Array增加方法

     every , some , forEach , filter , indexOf , lastIndexOf , isArray , map , reduce , reduceRight

        PS: 还有其他方法 Function.prototype.bindString.prototype.trimDate.now

      3. Object方法

    Object.getPrototypeOf
    Object.create
    Object.getOwnPropertyNames
    Object.defineProperty
    Object.getOwnPropertyDescriptor
    Object.defineProperties
    Object.keys
    Object.preventExtensions / Object.isExtensible
    Object.seal / Object.isSealed
    Object.freeze / Object.isFrozen
        PS:只讲有什么,不讲是什么。

        ~~2019/03/14补充~~

       Object.defineProperty()

       defineProperty方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象。 

       Object.defineProperty(obj对象, prop属性名称, descriptor属性描述符)

    二、什么是ES6

      附上学习地址:http://es6.ruanyifeng.com/

      ECMAScript6(2015.6.17)在保证向下兼容的前提下,提供大量新特性,目前浏览器兼容情况如下:(can i use 提示尝试搜索单个特性查看支持情况...)

      ES6特性如下:

      1.块级作用域

        关键字 let

        常量const

      2.对象字面量的属性赋值简写(property value shorthand)  

    var obj = {
        // __proto__
        __proto__: theProtoObj,
        // Shorthand for ‘handler: handler’
        handler,
        // Method definitions
        toString() {
        // Super calls
        return "d " + super.toString();
        },
        // Computed (dynamic) property names
        [ 'prop_' + (() => 42)() ]: 42
    };

      3.赋值解构

    let singer = { first: "Bob", last: "Dylan" };
    let { first: f, last: l } = singer; // 相当于 f = "Bob", l = "Dylan"
    let [all, year, month, day] =  /^(dddd)-(dd)-(dd)$/.exec("2018-12-12");
    let [x, y] = [1, 2, 3]; // x = 1, y = 2

        例子如下:

        ~~2019/03/14补充~~

        变量赋值解构可以做变量值的交换,不需要中间变量,看下例:

            let e = 50, f = 60; 
            [e, f] = [f, e];
            console.log(e, f);  //60,50

       4.函数参数 - 默认值、参数打包、 数组展开(Default 、Rest 、Spread)  

        注意:

        默认值参数指定后,length属性不再起效;

        rest 参数之后不能再有其他参数(即只能是最后一个参数),否则会报错。

    //Default
    function findArtist(name='lu', age='26') {
        //todo
    }
    
    //Rest
    function f(x, ...y) {
      // y is an really Array
      return x * y.length;
    }
    f(3, "hello", true) == 6
    
    //Spread
    function f(x, y, z) {
      return x + y + z;
    }
    // Pass each elem of array as argument
    f(...[1,2,3]) == 6

      5.箭头函数 Arrow functions  (=>)  

        5.1.简化了代码形式,默认return表达式结果,

        5.2.自动绑定语义this,即定义函数时的this

        5.3不可以使用new命令,否则会抛出一个错误,

        5.4不可以使用arguments对象,该对象在函数体内不存在

    var sum = (num1, num2) => { return num1 + num2; }
    sum(1,2);
    // return 3
    // 等同于
    var sum = function(num1, num2) {
      return num1 + num2;
    };
    //按需输出0~10,闭包下
    for (var i = 0; i < 10; ++i) {
        setTimeout((i)=> {console.log(i)}, 0,i);
    }

       6.字符串模板 Template strings  

    var name = "Bob", time = "today";
    `Hello ${name}, how are you ${time}?`
    // return "Hello Bob, how are you today?"

      7. Iterators(遍历器)&  for..of  

        遍历器有个next方法,调用会返回:

          7.1.返回迭代对象的一个元素:{ done: false, value: 'hello' }

          7.2.如果已到迭代对象的末端:{ done: true, value: 'ending' }

    // return a b c
    for (var n of ['a','b','c']) {
      console.log(n);
    }

        for...of循环可以使用的范围包括数组、SetMap 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、第8点的 Generator 对象,以及字符串。

      8.Generators 

         Generator 函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同。

        ①function关键字与函数名之间有个星号*,

    function* helloWorldGenerator() {
      yield 'hello';
      yield 'world';
      return 'ending';
    }
    var hw = helloWorldGenerator();

        ②yield表达式,

        ③遍历器对象的方法

          参考遍历器的next()方法~

      9.Class语法糖

        Class,有constructor、extends、super,但本质上是语法糖(对语言的功能并没有影响,但是更方便程序员使用)。

        ~~2019/03/14补充~~

        Class有一个默认的构造函数constructor(),通过new生成实例对象时自动调用,其中this指向实例对象

    //代码没测试
    class Artist {
        constructor(name) {
            this.name = name;
        }
    
        perform() {
            return this.name + " performs ";
        }
    }
    
    class Singer extends Artist {
    
        constructor(name, song) {
            super.constructor(name);
            this.song = song;
        }
    
        perform() {
            return super.perform() + "[" + this.song + "]";
        }
    }
    
    let james = new Singer("Etta James", "At last");
    james instanceof Artist;     // true
    james instanceof Singer;     // true
    
    james.perform();     // "Etta James performs [At last]"

      10.Modules

        ES6的内置模块功能借鉴了CommonJSAMD各自的优点:

        10.1.具有CommonJS的精简语法、唯一导出出口(single exports)和循环依赖(cyclic dependencies)的特点。

        10.2.类似AMD,支持异步加载和可配置的模块加载。

    // lib/math.js
    export function sum(x, y) {
      return x + y;
    }
    export var pi = 3.141593;
    
    // app.js
    import * as math from "lib/math";
    alert("2π = " + math.sum(math.pi, math.pi));
    
    // otherApp.js
    import {sum, pi} from "lib/math";
    alert("2π = " + sum(pi, pi));
    
    Module Loaders:
    // Dynamic loading – ‘System’ is default loader
    System.import('lib/math').then(function(m) {
      alert("2π = " + m.sum(m.pi, m.pi));
    });
    
    // Directly manipulate module cache
    System.get('jquery');
    System.set('jquery', Module({$: $}));     // WARNING: not yet finalized

      11.Map & Set & WeakMap & WeakSet  

        四种集合类型,WeakMap、WeakSet作为属性键的对象如果没有别的变量在引用它们,则会被回收释放掉。

    // Sets
    var s = new Set();
    s.add("hello").add("goodbye").add("hello");
    s.size === 2;
    s.has("hello") === true;        //true
    
    // Maps
    var m = new Map();
    m.set("hello", 42);
    m.set(s, 34);
    m.get(s) == 34;        //true
    
    //WeakMap
    var wm = new WeakMap();
    wm.set(s, { extra: 42 });
    wm.size === undefined
    
    // Weak Sets
    var ws = new WeakSet();
    ws.add({ data: 42 });    //Because the added object has no other references, it will not be held in the set

      12.Math + Number + String + Array + Object APIs  

        一些新的API

    //数值的扩展
    Number.EPSILON   Number.isInteger(Infinity)
    // false Number.isNaN("NaN") // false Math.acosh(3) // 1.762747174039086  双曲函数方法 Math.hypot(3, 4) // 5  平方和的平方根 Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
    //字符串的扩展 "abcde".includes("cd") // true "abc".repeat(3) // "abcabcabc"
    //数组的扩展 Array.from(document.querySelectorAll('*')) // Returns a real Array Array.of(1, 2, 3) // [1,2,3] 将一组值转换为数组 [0, 0, 0].fill(7, 1) // [0,7,7] [1, 2, 3].find(x => x == 3) // 3 [1, 2, 3].findIndex(x => x == 2) // 1 [1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2] ["a", "b", "c"].entries() // 遍历键值对[0, "a"], [1,"b"], [2,"c"] ["a", "b", "c"].keys() // 遍历键名 0, 1, 2 ["a", "b", "c"].values() // 遍历键值 "a", "b", "c"
    //对象的新增方法
    const target={a:1};
    const source1 = { b: 2 };
    Object.assign(target, source1, {});  //{a: 1, b: 2}
    //Object.assign(Point, { origin:
    new Point(0,0) })

      13. Proxies  Proxy

        使用代理(Proxy)监听对象的操作,然后可以做一些相应事情。

    var target = {};
    var handler = {
      get: function (receiver, name) {
        return `Hello, ${name}!`;
      }
    };
    
    var p = new Proxy(target, handler);
    p.world === 'Hello, world!';

        可监听的操作: get、set、has、deleteProperty、apply、construct、getOwnPropertyDescriptor、defineProperty、getPrototypeOf、setPrototypeOf、enumerate、ownKeys、preventExtensions、isExtensible

        ~~2019/03/14补充~~

        proxy对象用于定义基本操作的自定义行为(如属性查找,赋值,枚举,函数调用等),看下例:

    (function () {
            //proxy代理
            const data = {
                text2: '123'
            }
            const input = document.getElementById('app2-input');
            const app2Text = document.querySelector('.app2-text');
    
            const handler = {
                //监控数据变化
                set: function (target, prop, value) {
                    if (prop == 'text2') {
                        target[prop] = value; // 更新值
                        //以下更新视图
                        app2Text.innerHTML = value;
                        input.value = value;
                        return true;
                    } else {
                        return false;
                    }
                }
            }
            let app2 = new Proxy(data, handler); //构造proxy对象
    
            input.addEventListener('input', function (e) {
                app2.text2 = e.target.value;
            }, false)
        }());

      14.Symbols

        Symbol是一种基本类型。Symbol 通过调用symbol函数产生,它接收一个可选的名字参数,该函数返回的symbol唯一的。

    var key = Symbol("key");
    var key2 = Symbol("key");
    key == key2      //false

      15.Promises

        Promises是处理异步操作的对象,使用了 Promise 对象之后可以用一种链式调用的方式来组织代码,让代码更加直观(类似jQuerydeferred 对象)。

    function fakeAjax(url) {
      return new Promise(function (resolve, reject) {
        // setTimeouts are for effect, typically we would handle XHR
        if (!url) {
          return setTimeout(reject, 1000);
        }
        return setTimeout(resolve, 1000);
      });
    }
    
    // no url, promise rejected
    fakeAjax().then(function () {
      console.log('success');
    },function () {
      console.log('fail');
    });

    三、唠叨

      ECMAScript 8 (2017) 都发布一段时间了

      es7(2016)还没用上

      然而才来记es6&5的笔记

      ( ╯□╰ )逃走l..

      ╥﹏╥...头发又要抓掉一把了...

      写的不好地方&有错误的地方你告诉我,我.....我马上改,感谢指导~~~

  • 相关阅读:
    DZY Loves Sequences
    Boredom easy dp
    floyd算法 poj1125
    poj3259 Bellman_Ford算法
    poj1860 Bellman_Ford算法
    Java 获取资源文件路径
    CLion 2020.1.2 激活
    Kotlin学习笔记
    Kotlin Hello World
    WebStorm 2020.1.2 激活
  • 原文地址:https://www.cnblogs.com/anniey/p/10103971.html
Copyright © 2011-2022 走看看