Nodejs进阶系列-03- 类的定义

//01-类的定义

class Person {

    //构造函数 只允许一个构造器
    constructor(name,age) {
        this.name=name;
        this.age=age;
    }


    //类的方法
    say(){
        console.log(`this name is:${this.name} ,age: ${this.age} `); // 反引号的应用 tab+上面的那个键同时按
     }
     sing(){
         console.log("sing is runing.....")
     }

} //end Person


let person1 = new Person("张三丰",120);
person1.say();//this name is:张三丰 ,age: 120



//02-类的继承
   class Man extends Person{   //继承

        //子类不写构造器经测试也是可以的,它自动继承父类的。
        constructor(name,age) {
            super(name,age); //继承父类

        }

        //子类方法,父类中不存在
        play() {
            console.log(`${this.name} now start playing...... `); // 反引号的应用 tab+上面的那个键同时按
        }

        //如果这里也定义了say()方法和主类相同的话,主类方法将被过载。
        // say() {
        //     console.log("我重载了父类的方法!")
        //  }

        //如果这里定义say(带参数),执行时即时不带参数执行,也是执行子类的say()方法,不会执行主类的say();
         // say(worker) {
         //     console.log("我重载了父类的方法"); // 反引号的应用 tab+上面的那个键同时按
         // }

   }


 let man = new Man("刘德华",53);
  man.say();//this name is:刘德华 ,age: 53
  man.play();//刘德华 now start playing......
发布了40 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/LUCKWXF/article/details/104149154