class可以看做就是一个语法糖,完全可以理解成es5中构造函数的另一种写法。
每个class都会有一个constructor函数,不写的话,js默认会加上一个空的constructor函数。
class与es5构造函数的区别
1.class内部是严格模式,其实es6推崇的都是严格模式,什么是严格模式呢,大致理解就是写法更加的规范,
eg: 不能使用未声明的变量,不能使用关键字和保留字,不允许对只读属性赋值,等等。。。
// es5中
x=5
console.log(x) //5
function Per () {
"use strict"
y = 3.14 //报错
}
2. 变量提升
es5中function 和var都会进行提升, es6中class不会进行提升
new Foo(); //报错
class Foo {}
3.this指向
es5中谁调用该方法,改方法的this指向谁
es6中class中如果含有this,其默认指向类的实例
4.静态方法写法区别
es5中静态方法和静态属性
function A(){
a = 1
}
A.sayMeS=function(){
console.log("Hello World S!");
}
es6中静态方法和静态属性
class B {
static sayMes = function () {
console.log('456')
}
}
B.Foo = 'foo'
class中属性和方法不可枚举
class Point {
constructor(x, y) {
// ...
}
toString() {}
}
Object.keys(Point.prototype, 'Point')
console.log(Object.keys(Point.prototype),'Point') // []
function Pe () {
}
Pe.prototype.toString = function() {
}
console.log(Object.keys(Pe.prototype), 'Pe') // ["toString"]
继承
es5中实现继承就是修改原型链
es6中class利用extends关键字实现继承,class中实现继承要调用super方法,super方法只能在constructor中调用,在其他地方调用会报错,在子类class中super相当于父类的构造函数,调用super相当于调用父类的constructor函数。所以调用super方法后才能实现继承,这种继承相当于把父类copy了一份给子类。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static haha () {
console.log('haha')
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
this.color = color; // 报错,constructor中使用this要在super调用之后,因为子类不存在this,要super调用后继承父类子类才会存在this
super(x, y);
console.log(this.x, y)
this.color = color; // 正确
}
sayHello () {
this.sayword ()
}
sayword () {
console.log('hello,word', this.x)
}
}
var b = new ColorPoint('x', 'y')
b.sayHello()
b.haha() //报错,haha是静态方法,实例中无法访问
ColorPoint.haha() // 打印haha,ColorPoint继承父类,相当于copy一份父类,所以ColorPoint中存在静态方法haha
class中super用两种使用形式,第一种是当函数使用,代表父类的构造函数 ,第二种是当做对象使用,super
作为对象时,在普通方法中,指向父类的原型对象(partent.prototype);在静态方法中,指向父类(partent)。
class A {
constructor() {
this.p = 2;
}
}
class B extends A {
get m() {
return super.p;
}
}
let b = new B();
b.m //undefined
// super在普通方法中指向父类原型,而父类A中的p在实例上,不是在原型中,所以子类B中super.p (相当于A.prototype.p)打印出undefined