<script>
//1.创建class类
class Star{
constructor(uname,age){
this.uname = uname;
this.age = age;
}
sing(song){
console.log(this.uname + song);
}
money(){
console.log(this.x + this.y);
}
}
class Son extends Star{ //子类继承父类的方法
constructor(x,y){
super(); //调用父类中的构造函数
}
}
var son = new Son(1,3);
son.money();
//继承中,如果实例化子类输出一个方法,先看子类中有没有这个方法,如果有就先执行子类的
//2.利用类创建对象new
var xm = new Star('小明',15);
var xh = new Star('小红',15);
console.log(xm);
console.log(xh);
xm.sing('bbb');
xh.sing('aaa');
//通过class关键字创建类,类名习惯性定义大写
//类里面有个constructor函数,可以接受参数,同时返回实例对象
//constructor函数只要new生成实例时,就会自动调用这个函数
//生成实例new不可以省略
</script>
<script>
class Father{
constructor(x, y){
this.x = x;
this.y = y;
}
sum(){
console.log(this.x + this.y);
}
}
class Sen extends Father{
constructor(x, y){
super(x, y); //子类使用super调用父类构造函数必须放到this前面
this.x = x;
this.y = y;
}
subtract(){
console.log(this.x - this.y);
}
}
var son = new Sen(5,3);
son.subtract();
son.sum();
//在ES6中类没有变量提升,所以必须先定义,才能通过类实例化对象
//类里面的公有方法和属性一定要加this使用
//insertAdjacentHTML('beforeend', li); ===appnedChild
</script>
类和对象
最新推荐文章于 2023-06-15 17:30:06 发布