es6声明一个类

时间:2023-03-10 02:16:12
es6声明一个类

js语言的传统方式是通过定义构造函数,生成心得对象。是一种基于原型的面向对象系统。在es6中增加了class类的概念,可以使用class关键字来声明一个类。之后用这个类来实例化对象。

构造函数示例

es6声明一个类
const Demo = function(a,b){
this.a = a;
this.b = b;
return this;
} Demo.prototype = {
constructor: Demo,
print: function(){
console.log(this.a+this.b);
}
} const demo = new Demo('jane','yun').print();
es6声明一个类
es6声明一个类
class Demo {
constructor(a,b){
this.a = a;
this.b = b;
return this;
}
print(){
console.log(this.a+this.b);
}
} const demo = new Demo('hello','world').print();
es6声明一个类

Demo中的constructor是构造方法,this关键字代表示例对象。

注:定义类的方法的时候不需要写function,另外 也不需要逗号。

2:静态方法

es6声明一个类
class Point{
constructor(a,b){
this.a = a;
this.b = b;
return this;
}
static print(){
console.log('say hi');
}
} const Point.print();
es6声明一个类

3:继承

es6声明一个类
class A{
constructor(a){
this.a = a;
return this;
}
string(){
return 'hello,'+ this.a
}
} class B extends A{
constructor(a){
super();
}
m(){
super.sting();
}
} const b = new B(3);
es6声明一个类
super
  1、super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。
  2、super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类
  super代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B,因此super()在这里相当于A.prototype.constructor.call(this)。
分类: javascript