类抽象了对象公共部分,泛指某一大类(class) 对象特指某一个,通过类实例化一个具体的对象
ES6引入了Class这个概念,作为对象的模板。通过class关键字,可以定义类。ES6 的class可以看作只是一个语法糖。
class star{}
star.prototype.sum = function(){
console.log("a");
}
console.log(typeof star); //function
console.log(star.prototype); //sum: ƒ ()
console.log(star.prototype.constructor); //class star{}
constructor()
constructor()方法是类的构造函数(默认方法),用于传递参数,返回实例对象,通过new命令生成对象实例时,自动调用该方法。如果没有显示定义,类内部会自动给我们创建一个constructor()
//创建一个新类
class Star{
constructor(name,age){ //生成new时,自动调constructor(不写也调),生成的实例对象用zs接收
this.name = name;
this.age = age;
}
//添加新方法
say(){
console.log("me");
}
}
// 用类生成一个对象,类必须使用new调用
var zs = new Star("zs",20)
console.log(zs);
zs.say()
继承
//创建一个新类
class Star{
constructor(){ }
say(){
console.log('hello');
}
}
class newStar extends Star{}
var zs = new newStar()
zs.say()
多态
利用super调用父类中的方法。 super可调用父类中的方法(直接调用也行)
class Star{
constructor(x,y){
this.x = x
this.y = y
}
say(){
console.log(this.x + this.y);
}
}
class newStar extends Star{
constructor(x,y){
super(x,y)
}
}
var zs = new newStar(1,2)
zs.say()
super调用父类构造函数,必须在this之前
class Star{
constructor(x,y){
this.x = x
this.y = y
}
say(){
console.log(this.x + this.y);
}
}
class newStar extends Star{
constructor(x,y){
//super调用父类构造函数,必须在this之前
super(x,y)
this.x = x
this.y = y
}
sing(){
console.log("sing");
}
}
var zs = new newStar(1,2)
zs.say()
zs.sing()