简介
ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了。它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应用程序,成为企业级开发语言。
ES6新增及和ES5的不同
变量:
ES5:
定义变量使用var
- 变量进行变量提升
- 同一作用域下可以声明同名变量(而let和const不可以)
ES6:
定义变量加入了 let const
1.使用let来定义变量
- 在变量声明前引用变量会造成错误。
2.使用const来定义变量
- const定义的常量不可修改 且不能为null
- 可以修改复杂数据类型
总结:可以使用let和const代替var,尽量使用const来定义变量,如果变量在后续代码中需要更改变化,则使用let来进行声明。
封闭空间:
ES5:
ES5中用封闭函数也就是立即执行函数来创建封闭空间
(function closeSpace(){
alert('hello!')
})()
//还可以在函数定义前加上“~”和“!”等符号来定义匿名函数
!function closeSpace(){
alert('hello!')
}()
~function closeSpace(){
alert('hello!')
}()
/*封闭函数可以创造一个独立的空间,在封闭函数内定义的变量和函数不会影响外部同名的函数和变量,可以避免环境污染和命名冲突。*/
ES6:
为了避免污染全局环境污染不必再使用封闭空间,在局部环境中使用let来定义变量就可以解决所有问题。
模板字符串:
变量以及字符串的拼接
ES5:
/*字符串和变量的拼接:变量不加'',字符串加'',字符串和变量的拼接使用加号*/
var name=Reborn;
var age=22;
alert('My name is'+name+',He is'+age);
ES6:
ES6可以使用新增的模板字符串来进行变量和字符串的拼接
const name=Reborn;
const age=22;
alert(`My name is ${name},He is ${age}`);
类和面向对象:
在 JavaScript 中,每个对象都有原型对象。所有 JavaScript 对象都从原型上继承方法和属性。
- ES5中,属性放在构造函数(constructor)里,方法放在原型(prototype)上;
1.ES6中引入了类(class)来代替构造函数
ES5:
function Person(name,age){
this.name=name;
this.age=age;
}
//在原型上挂载showName方法
Person.prototype.showName=function(){
return this.name;
}
var P = new Person('Reborn','18');
alert(P.showName());//Reborn
ES6:
class Person {
constructor(name) {
this.name = name;
}
showName() {
return this.name;
}
}
const P = new Person('Reborn');
alert(P.showName()); //Reborn
2.继承:提供了新的关键字 extends 和 super
ES5:
function Person (name,age){
this.name = name;
this.age = age;
}
Person.prototype.showName = function(){
return this.name;
};
Person.prototype.showAge = function(){
return this.age;
};
function Worker (name,age,job){
//属性继承
Person.call(this,name,age);
//Person.apply(this,arguments);
this.job = job;
}
//方法继承
Worker.prototype = new Person();
Worker.prototype.constructor = Worker;
Worker.prototype.showJob = function(){
return this.job;
};
//
var W = new Worker('Reborn',22,'秃头患者');
alert(W.showJob());//秃头患者
ES5:
class Person {
constructor(name,age) {
this.name = name;
this.age=age;
}
showName() {
return this.name;
}
showAge(){
return this.age;
}
}
class Worker extends Person {
constructor(name,age,job){
super(name,age);
this.job=job;
}
showJob(){
return this.job;
}
}
const W = new Worker('Reborn',22,'秃头患者');
alert(W.showJob()); // 秃头患者
中国加油!武汉加油!
疫情终将会结束,祖国的明天会越来越强大越来越美好!
by:逆战班1908-陈相宇
版权声明:本文为Reborn___原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。