ES6 class,与js prototype原型继承有何关系?

ES6为了进一步的缩减代码的编写,和简化代码的逻辑,引入了关键词 class。但class的实现也是在prototype的基础上,做了一层语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

class Person {
constructor(name) {
this.name=name||"Default";
}
toString(){
return 'Name:'+this.name;
}
}
var p1=new Person();
console.log(p1.name);
class Boy extends Person{
constructor(name){
super(name);
this.gende='Boy';
}
toString(){
return super.toString()+" - Gende:"+this.gende;
}
}
var b1=new Boy('hello');
console.log(b1);
console.log(b1.toString());

ES5的继承,也就是prototype
实质是先创造子类的实例对象this
然后再将父类的方法添加到this上面(Parent.apply(this))
ES6的继承,也就是class
实质是先创造父类的实例对象this(必须先调用super)
然后再用子类的构造函数修改this
它们的实现机制是不同的
ES6与 ES5 一样,类的所有实例共享一个原型对象

对于es6这一块,还是很有必要去读一读 文档的




原文链接:https://www.jianshu.com/p/fc4c2d8a0018

猜你喜欢

转载自blog.csdn.net/wy_Blog/article/details/79457206