zoukankan      html  css  js  c++  java
  • 14.class类

    在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。

    class 的本质是 function。

    它可以看作一个语法糖,让对象原型的写法更加清晰、更像面向对象编程的语法。

    基础用法

    类定义

     // es5造类
            function Person(name,age) {
                this.name = name;
                this.age = age;
            }
            Person.prototype.sayName = function() {
                return this.name;
            }
            let p1 = new Person('小马哥',28);
            console.log(p1);
    
    //  es6造类      
            class Person {
                // 实例化的时候会立即被调用
                constructor(name, age) {
                    this.name = name;
                    this.age = age;
                }
            }

    类的继承 extends

    class Animal{
                constructor(name,age) {
                    this.name = name;
                    this.age = age;
                }
                sayName(){
                    return this.name;
                }
                sayAge(){
                    return this.age;
                }
            }
    
            class Dog extends Animal{
                constructor(name,age,color) {
                    super(name,age);
                    // Animal.call(this,name,age);
                    this.color = color;
                }
                // 子类自己的方法
                sayColor(){
                    return `${this.name}是${this.age}岁了,它的颜色是${this.color}`
                }
                // 重写父类的方法
                sayName(){
                    return this.name + super.sayAge() + this.color;
                }
                
            }
            let d1 = new Dog('小黄',28,'red');
            console.log(d1.sayColor());
            console.log(d1.sayName());
    

      

  • 相关阅读:
    RAND函数和SRAND函数
    称丢手帕问题
    用GDB调试程序(七)
    用GDB调试程序(六)
    用GDB调试程序(三)
    用GDB调试程序(五)
    用GDB调试程序(二)
    用GDB调试程序(一)
    SOAP 简单对象访问协议
    关于angularJS绑定数据时自动转义html标签
  • 原文地址:https://www.cnblogs.com/sunny666/p/12986736.html
Copyright © 2011-2022 走看看