JS-类和继承

类和继承

1.类

		class Person {
            constructor(uname, age) {
                this.uname = uname
                this.age = age
            }

            eat() {
                console.log('吃');
            }
        }

        let zs = new Person('张三', 18)
        zs.eat()
    1.本质:类在本质上就是构造函数的新写法
    2.作用:用来创建对象
    3. 使用:
        class 类名 {
            constructor(形参,形参...) {
                this.形参 = 形参
                this.形参 = 形参
                ...
            }

            函数名() {

            }
        }
     4. 注意:
         1)类的属性必须通过constructor设置
         2)类中方法的设置在constructor外部添加一个函数,函数不能有function
         3)类中的方法默认添加到prototype上
         4)通过类创建对象时,程序会默认执行constructor中代码
         5)类名遵守帕斯卡命名法
         6)类中的方法和属性相互访问要加上this
            this.属性
            this.方法()

2.继承

		class Person {
            constructor(uname, age, gender) {
                this.uname = uname
                this.age = age
                this.gender = gender
            }

            eat() {
                console.log('吃');
            }
        }

        class Student extends Person {
            constructor(uname, age, gender, score) {
                super(uname, age, gender)
                this.score = score
            }
            test() {
                console.log(this.uname + '考试' + this.score + '分');
                this.aword()
            }

            aword() {
                console.log('爸爸奖励了' + this.uname + '100元');
            }

            punish() {
                console.log('爸爸奖励了一耳光');
            }
            eat() {
                console.log('吃苹果');
            }
        }

        let zs = new Student('张三', 18, '男', 150)
        zs.test()
        zs.eat()
    1) 继承语法
    class 子类 extends 父类 {
        constructor() {
            super()
        }
    }
    2) 父类中的形参通过super传送, constructor要填入所有参数
    3) 子类的方法可以和父类方法同名, 覆盖父类的方法
    4) 类中的属性和方法相互访问要加上this
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值