初探ECMAScript6

简介:

基础变化

  1. String类型新增了三个方法,不必使用indexOf来判断一个字符串是否在另一个字符串内 

//String changes
var a = "Hello world";
    var b = "Hello";
    var c = "world";
    function includes(source, dest) {
      return source.indexOf(dest) > -1;
    }
    function startsWith(source, dest) {
      return source.slice(0, dest.length) === dest;
    }
    function endsWith(source, dest) {
      return source.slice(source.length - dest.length, source.length) === dest;
    }

var msg = "Hello world!";

    console.log("msg startsWith Hello: ", msg.startsWith("Hello"));       // true
    console.log("msg endsWith !: ", msg.endsWith("!"));             // true
    console.log("msg includes o:  ", msg.includes("o"));             // true
    
    console.log("msg startsWith o: ", msg.startsWith("o"));           // false
    console.log("msg endsWith world!: ", msg.endsWith("world!"));        // true
    console.log("msg includes x:  ", msg.includes("x"));             // false

  1. Object.is方法用来判断两个参数是否相等,与全等(===)类似只是在+0和-0上以及NaN与NaN的判断上与全等不同 

console.log(+0 == -0);              // true
console.log(+0 === -0);             // true
console.log(Object.is(+0, -0));     // false

console.log(NaN == NaN);            // false
console.log(NaN === NaN);           // false
console.log(Object.is(NaN, NaN));   // true

console.log(5 == 5);                // true
console.log(5 == "5");              // true
console.log(5 === 5);               // true
console.log(5 === "5");             // false
console.log(Object.is(5, 5));       // true
console.log(Object.is(5, "5"));     // false

  1. let声明,let与var的作用相同,只是以let声明的变量的作用域在当前的{}块内 

function getValue(condition) {

    if (condition) {
        let value = "blue";

        // other code

        return value;
    } else {

        // value doesn't exist here

        return null;
    }

    // value doesn't exist here
}

  1. const关键字用来声明常量,常量一旦赋值就无法改变,其他的赋值表达式都会被忽略
  2. 解构赋值,引入解构赋值可以方便的从复杂的对象中取得所需的属性值 

var options = {
        repeat: true,
        save: false,
        rules: {
            custom: 10,
        }
    };

// later

var { repeat, save, rules: { custom }} = options;

console.log(repeat);        // true
console.log(save);          // false
console.log(custom);        // 10

  1. 类声明语法,目前许多前端框架比如dojo、extJs使用辅助设计使得Javascript看起来支持“类”,基于以上目的ES6引入类体系;目前在Chrome使用class关键字必须使用严格模式 

//class declaration
function PersonType(name) {
        this.name = name;
    }
    
    PersonType.prototype.sayName = function() {
        console.log(this.name);
    };
    
    let person = new PersonType("Nicholas");
    person.sayName();   // outputs "Nicholas"
    
    console.log(person instanceof PersonType);      // true
    console.log(person instanceof Object);      // true

(function(){
'use strict';
class PersonClass {
        constructor(name) {
            this.name = name;
        }
        sayName() {
            console.log(this.name);
        }
    }
    
    let person = new PersonClass("Nicholas");
    person.sayName();   // outputs "Nicholas"
    
    console.log(person instanceof PersonClass);     
    console.log(person instanceof Object);  
})()

  1. 属性访问器,通过使用get和set关键字来声明属性(Attribute),在ES5中需要借助Object.defineProperty来声明属性访问器 

//Accessor Properties
(function(){
      'use strict';
      class PersonClass {
        constructor(name) {
            this.name = name;
        }
        get Name(){
          return this.name;
        }
        set Name(value){
          this.name = value;
        }
      }
    
      let person = new PersonClass("Nicholas");
      console.log('person.Name: ', person.Name)   // outputs "Nicholas"
    })()

  1. 静态成员,ES5或者之前的代码通过在构造函数中直接定义属性来模拟静态成员;ES6则只需要在方法名前面加上static关键字 

//ES5
function PersonType(name) {
    this.name = name;
}

// static method
PersonType.create = function(name) {
    return new PersonType(name);
};

// instance method
PersonType.prototype.sayName = function() {
    console.log(this.name);
};

var person = PersonType.create("Nicholas");

//ES6
//Static Members
(function(){
      'use strict';
      class PersonClass {
        constructor(name) {
          this.name = name;
        }
          
        sayName() {
          console.log(this.name);
        }
        
        static create(name) {
          return new PersonClass(name);
        }
      }
      
      let person = PersonClass.create("Nicholas");
      console.log(person);
    })()

  1. 继承,ES5中需要借助prototype属性而ES6中引入extends关键字来实现继承 

//Handling Inheritance
(function(){
      'use strict';
      class PersonClass {
        constructor(name) {
          this.name = name;
        }
      }
      
      class Developer extends PersonClass {
        constructor(name, lang) {
          super(name);
          this.language = lang;
        }
      }
      
      var developer = new Developer('coder', 'Javascript');
      console.log("developer.name: ", developer.name);
      console.log("developer.language: ", developer.language);
    })()

模块机制

  当前关于JS的模块化已有两个重要的规范CommonJs和AMD,但毕竟不是原生的模块化,所以ES6中引入模块化机制,使用export和import来声明暴露的变量和引入需要使用的变量

  

 

Iterator和Generator

  Iterator拥有一个next方法,该方法返回一个对象,该对象拥有value属性代表此次next函数的值、done属性表示是否拥有继续拥有可返回的值;done为true时代表没有多余的值可以返回此时value为undefined;Generator函数使用特殊的声明方式,generator函数返回一个iterator对象,在generator函数内部的yield关键字声明了next方法的值


//Iterator & Generator
// generator
    function *createIterator() {
        yield 1;
        yield 2;
        yield 3;
    }
    
    // generators are called like regular functions but return an iterator
    var iterator = createIterator();
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());

Promise

  ES6引入原生的Promise对象,Promise构造函数接受一个方法作为参数,该方法中可以调用resolve和reject方法,分别进入fulfill状态和fail状态


// Promise
var getJSON = function(url) {
  var promise = new Promise(function(resolve, reject){
    var client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.send();

    function handler() {
      if (this.readyState !== 4) {
        return;
      }      
      if (this.status === 200) {
      debugger;
        resolve(this.responseText);
      } else {
        reject(new Error(this.statusText));
      }
    };
  });

  return promise;
};

getJSON("https://gis.lmi.is/arcgis/rest/services/GP_service/geocode_thjonusta_single/GeocodeServer?f=json").then(function(json) {
  console.log('Contents: ' + json);
}, function(error) {
  console.error('Error: ', error);
});

Proxy

  顾名思义用来作为一个对象或函数的代理。Proxy构造函数接受两个参数:target用来被封装的对象或函数、handler拥有一系列方法,重写这些方法以便当调用这些操作时会进入重写的方法中

•handler.getPrototypeOf
•handler.setPrototypeOf
•handler.isExtensible
•handler.preventExtensions
•handler.getOwnPropertyDescriptor
•handler.defineProperty
•handler.has
•handler.get
•handler.set
•handler.deleteProperty
•handler.enumerate
•handler.ownKeys
•handler.apply
•handler.construct 

handler.getPrototypeOf
handler.setPrototypeOf
handler.isExtensible
handler.preventExtensions
handler.getOwnPropertyDescriptor
handler.defineProperty
handler.has
handler.get
handler.set
handler.deleteProperty
handler.enumerate
handler.ownKeys
handler.apply
handler.construct

 

参考资料:

Understanding ECMAScript 6

ECMAScript 6 入门


目录
相关文章
|
7天前
|
JavaScript 前端开发 API
ECMAScript和JavaScript的区别是什么?
【4月更文挑战第11天】ECMAScript和JavaScript的区别是什么?
12 1
|
8月前
|
JavaScript 网络架构
ECMAScript 6
解构赋值 1. 数组的解构赋值 2. 对象的解构赋值 3. 字符串的解构赋值 4. 数值和布尔值的解构赋值 ES6 字符串的扩展 1. 模板字符串 2.String.raw() 3.实例方法:padStart(),padEnd() ES6 函数的扩展 1. 函数参数的默认值 2.与解构赋值默认值结合使用 3. 函数的 length 属性 4. rest 参数 5. 箭头函数 ES6 数组的扩展
52 0
|
4月前
|
JavaScript 前端开发 安全
探索ECMAScript 2023:JavaScript的最新特性
探索ECMAScript 2023:JavaScript的最新特性
59 1
|
7月前
|
存储 Rust JavaScript
ECMAScript 2021 正式确认
ECMAScript 2021 正式确认
23 0
|
10月前
|
自然语言处理 JavaScript 前端开发
ECMAScript 6 新特性详解(上)
ECMAScript 6 新特性详解(上)
|
10月前
|
存储 前端开发 JavaScript
ECMAScript 6 新特性详解(下)
ECMAScript 6 新特性详解(下)
|
10月前
|
存储 JSON JavaScript
ECMAScript 6 新特性详解(中)
ECMAScript 6 新特性详解(中)
|
12月前
|
JavaScript 前端开发
ECMAScript 2015(ECMAScript 6)
ECMAScript 2015(ECMAScript 6)
58 0
|
缓存 JavaScript 前端开发
ECMAScript6入门上
ECMAScript6入门上
53 0
ECMAScript6入门上
|
JSON JavaScript 前端开发
ECMAScript6.0基础
1.什么是ES6 ECMAScript 6.0(以下简称ES6)是JavaScript语言的下一代标准,已经在2015年6月正式发布了。它的目标,是使得JavaScript语言可以用来编写复杂的大型应用程序,成为企业级开发语言。 标准的制定者有计划,以后每年发布一次标准,使用年份作为版本。因为ES6的第一个版本是在2015年发布的,所以又称ECMAScript 2015(简称ES2015)。
236 0
ECMAScript6.0基础