//定义一个类
class Person{
constructor(a){ //构造函数
this.name = a; //属性
}
state = "没有毛"; //属性
skill = function(){ //方法
console.log("直立行走");
}
}
let objPerson1 = new Person("易先生"); //实例化一个类的对象 objPerson1
console.log(objPerson1.name,objPerson1.state);
继承:
class Person{
constructor(a){ //构造函数
this.name = a; //属性
}
state = "没有毛"; //属性
skill = function(){ //方法
console.log("直立行走");
}
}
//创建一个子类并通过继承获得父类的属性和方法
class Itworker extends Person{
}
let objItworker1 = new Itworker("蓝镜");
console.log(objItworker1.name);
console.log(objItworker1.state);
objItworker1.skill();
子类中重写构造函数:
class Person{
constructor(a){ //构造函数
this.name = a; //属性
}
state = "没有毛"; //属性
skill = function(){ //方法
console.log("直立行走");
}
}
//创建一个子类并通过继承获得父类的属性和方法
class Itworker extends Person{
//子类中重写父类的构造函数
constructor(b){
this.aspect = b; //新属性
}
}
let objItworker1 = new Itworker("好看");
console.log(objItworker1.aspect); //输出子类中构造函数重新定义的新属性
console.log(objItworker1.state);
objItworker1.skill();
报错了!
我们来修正一下
class Person{
constructor(a){ //构造函数
this.name = a; //属性
}
state = "没有毛"; //属性
skill = function(){ //方法
console.log("直立行走");
}
}
//创建一个子类并通过继承获得父类的属性和方法
class Itworker extends Person{
//子类中重写父类的构造函数
constructor(a,b){ //加上父类构造函数的参数a
super(a); //父类的构造函数不能丢 还是要给它传一个参数过去
this.aspect = b; //新属性
}
}
let objItworker1 = new Itworker("蓝镜","好看");
console.log(objItworker1.name);
console.log(objItworker1.aspect); //输出子类中构造函数重新定义的新属性
console.log(objItworker1.state);
objItworker1.skill();
子类中重写父类的方法:
class Person{
constructor(a){ //构造函数
this.name = a; //属性
}
state = "没有毛"; //属性
skill = function(){ //方法
console.log("直立行走");
}
}
//创建一个子类并通过继承获得父类的属性和方法
class Itworker extends Person{
//子类中重写父类的构造函数
constructor(a,b){ //加上父类构造函数的参数a
super(a); //父类的构造函数不能丢 还是要给它传一个参数过去
this.aspect = b; //新属性
}
//子类中重写父类的方法
skill = function(){
console.log("搞别人的电脑");
}
}
let objItworker1 = new Itworker("易先生","兵哥哥");
console.log(objItworker1.name);
console.log(objItworker1.aspect); //输出子类中构造函数重新定义的新属性
console.log(objItworker1.state);
objItworker1.skill();
以上就是JS中类的创建,继承,以及子类中构造函数的重写和方法的重写。