一、新增数据类型
ES5中的数据类型有:undefined、null、object、number、string、boolean、function;
ES6中新增数据类型:symbol
ES6中新增类数据结构:class
1、symbol
概述:新的数据类型,表示独一无二的值;
(1)基本用法
Symbol函数的参数只是表示对当前Symbol值的描述,因此相同的参数的Symbol函数返回的值是不相等的。
let s = Symbol();
typeof s;//"symbol"
let st = Symbol('s');
Symbol值不能与其他类型的值进行运算,回报错。
let s = Symbol('s');
"your symbol value is " + s;//TypeError
Symbol可以显式的转换为字符串
let s = Symbol('s');
String(s);//'Symbol(s)'
Symbol值可以转换为布尔值,但不可转换为数值
let s = Symbol('s');
Boolean(s);//true
Number(s);//TypeError
(2)Symbol.for(),Symbol.keyFor()
Symbol.for():每次调用该方法都会先检查给定但key值是否存在,如果不存在新建一个值。
Symbol.for('s') == Symbol.for('s');//true
Symbol('b') == Symbol('b');//false
Symbol.keyFor():方法返回一个已登记的 Symbol 类型值的key。
let s = Symbol.for('s');
Symbol.keyFor(s);//'s'
let s1 = Symbol('b');//Symbol没有注册机制
Symbol.keyFor(s1);//undefined
2、class
概述:语法糖,使得JavaScript更像面向对象语言。
(1)基本用法
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return '(' + this.x + ', ' + this.y + ')';
}
}
类所有但方法都定义在类的prototype属性上面,类和模块的内部,默认就是严格模式,所以不用使用use strict指定运行模式。
Point.prototype = {
constructor(){},
toString(){}
}
类必须使用new调用,否则会报错。
Point();//TypeErroe
(2)constructor方法
默认返回实例对像(即this),也可以指定返回另一个对象。
class Point{
contructor(){
return Object.create(null);
}
}
typeof Point;//'function'
new Point() instanceof Point;//false
一个类必须有constructor
方法,如果没有显式定义,一个空的constructor
方法会被默认添加。
class Point{
}
//等同于
class Point{
constructor(){}
}
(3)class表达式
const Myclass = class Me{
getClassName(){
return Me.name;
}
}
//或者
const Myclass = class{};
//class立即执行表达式
let point = new class{
contructor(x,y){this.x = x;this.y = y;}
}(1,1);
类不存在变量提升,在使用之前必须先定义类。ES6不提供私有方法,需要采用变通的方法。ES6同样不支持私用属性。
(4)class的静态方法
不会被实例继承,可以直接使用类调用的方法,使用static关键字进行定义。
class Point{
static classStatic(){
return 'Hello Static Method!';
}
}
Point.classStatic();//Hellp Static Method!
let point = new Point();
point.classStatic();//TypeError
静态方法中使用的this关键字,this是指向class,而不是实例。父类的静态方法,可以被子类继承。也可以通过super对象调用。
(5)new.target属性
返回new命令用作那个构造函数,如果不是通过new命令调用的,则返回undedined
class Point{
constructor(x,y){
this.x = x;
this.y = y;
if(new.target == Point){throw new Error("不可实例化该类!");}
}
}
class SonPoint extends Point{
constructor(x,y,z){
super(x,y);
this.z = z;
}
}
(6)class的继承
通过extends关键字实现继承。
class Point{}
class sonPoint extends Point{}
super关键字即可以当作函数调用,也可以当作对象使用。作为函数调用时,代表父类的构造函数。作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
ES6要求子类构造函数必须执行一次super函数。
class Point{}
class SonPoint{
constructor(){
super();
}
}