今天说一下什么是es6中的类
image
1.首先说一下用class生成的类
//生成实例对象的传统方法是通过构造函数
function Point(x,y){
this.x = x;
this.y = y
}
Point.prototype.toString = function(){
return '(' + this.x+','+this.y+')'
}
var p = new Point(1,2);
//ES6 提供了更接近传统语言的写法 引入了Class类这个概念 ES6 的Class可以看作只是一个语法糖
class Point{
constructor(x,y){ //构造方法
this.x = x;
this.y = y;
}
toString(){
return '('+this.x + ',' +this.y+')';
}
}
//ES6的类 完全可以看做构造函数的另一种写法
//使用的时候 也是直接对类使用new命令,跟构造函数用法完全一致
//事实上类的所有方法都在类的prototype属性上面
//所以 类.prototype.constructor === 类 true
//constructor方法是类我的默认方法,通过new命领生成对象实例时,自动调用该方法
//一个类必须拥有constructor这个方法 如果没有的话自动添加 所以
class Point{
}
//等同于
class Point{
constructor(){}
}
//constructor方法默认返回实例对象
//就像使用构造函数一样运用
var point = new Point()
2.继承
// 继承
class Parent{ //定义一个类
constructor(name='小明'){
this.name= name;
}
}
class Child extends Parent{
}
console.log('继承',new Child()) // 继承 {name: "小明"}
继承传递参数
// 继承传递参数
class Parent{ //定义一个类
constructor(name='小明'){
this.name= name;
}
}
class Child extends Parent{
constructor(name = 'child'){ // 子类重写name属性值
super(name); // 子类向父类修改 super一定放第一行
this.type= 'preson';
}
}
console.log('继承',new Child('hello')) // 带参数覆盖默认值 继承{name: "hello", type: "preson"}
3.类的super()方法
super关键字出现的前提是使用Class的继承
class Person { // ... }
class Student extends Person{
constructor(){
super();
}
}
为什么会有super
当类使用继承,并实例化时,
es5 的继承是先创建子类的this,然后将父类的方法添加到子类的this上去;
es6 的继承是创建父类的this对象,然后再对this对象添加方法/属性。
而super方法就是用来创建父类this对象的。
使用super()
const proto = {
foo: 'hello'
};
const obj = {
foo: 'world',
find() {
return super.foo;
}
};
Object.setPrototypeOf(obj, proto);//使用setPrototypeOf给obj设置原型对象为proto
obj.find() // "hello"
注意:super用来表示原型对象时,只能用在对象的方法中,用在其他地方都会报错。
静态方法调用
静态方法中的super指向父类
class Person {
static sport(str) {
console.log(str);
}
}
class Student extends Person {
static log() {
super.sport('调用到啦!!!');
}
}
Student.log(); // 调用到啦!!!
ES6 规定,通过super调用父类的方法时,方法内部的this指向子类。
实际上执行的是 super.sport.call(this);