ES6的类和对象

类的构造函数constructor( ),用于传递参数,返回实例对象,通过new生成对象实例时,自动调用该方法。若未定义,系统会自动创建。

注意:在es6中类没有变量的提升,所以只有必须先定义类,才能通过类实例化对象。在类里面共有的属性和方法一定要加this使用。

语法:class name{ }

创建一个实例并在类中写入共有方法:

<body>
<script>
    class Star{
        constructor(uname,uage){
            this.uname = uname;
            this.uage = uage;
        }
        //类里面函数不需要添加function
        sing(song){
            console.log(this.uname+song);
        }
    }
    var ldh = new Star("刘德华",28);
    console.log(ldh);
    ldh.sing("冰雨");
</script>
</body>

注意:   1) 其中this指向的是创建的实例ldh    2) 只要new,就会调用构造函数

继承 extends super

<script>
class Father{
    constructor(){}
    money(){
        console.log(100);
    }
}
class Son extends Father{ }
var son = new Son();
son.money();
</script>

警惕:下面的这段错误,应该使用super:

<script>
class Father{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
    sum(x,y){
        console.log(this.x+this.y);
    }
}
class Son{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
}
var son = new Son(1,2);
son.sum( );
</script>

使用super:super关键字用于访问和调用对象父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数。

注意:super必须在子类this之前调用,方可调用父类中的sum方法

<script>
    class Father{
        constructor(x,y){
            this.x = x;
            this.y = y;
        }
        sum(){
            console.log(this.x+this.y);
        }
    }
    class Son extends Father{
        constructor(x,y){
            super(x,y);//调用父类中的构造函数,注意:super必须在子类this之前调用,方可调用父类中的sum方法
            this.x = x;
            this.y = y;
        }
        sub(){
            console.log(this.x - this.y);
        }
    }
    var son = new Son(5,3);
    son.sub();
    son.sum( );
</script>

继承原则

继承的属性或者方法查找原则是就近原则。

继承中,如果实例化子类输出一个方法,先看子类中是否有这个方法,如果有就先执行子类的方法;如果没有就去查找父类的方法。

实例:

<script>
class Father{
    say(){
      return   "我是爸爸";
    }
}
class Son extends Father{
    say(){
        // console.log("我是儿子");//输出:我是儿子
        console.log(super.say()+'的儿子');//输出:我是爸爸的儿子
    }
}
var son = new Son();
son.say( );
</script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值