面向对象

98 阅读1分钟

1.创建对象

    // 通过class 关键词创建一个类,类名习惯性首字母大写
    // 类中有constructor 函数,可以同接收参数
    // constructor 相当于之前学习的构造函数!!!!
    // 生成实例,使用new关键词!!!
        class Person {
            constructor(name,age){
                this.name = name;
                this.age = age;
            }
            
        }
        var ldh = new Person('刘德华','18');
        var pcj = new  Person('潘长江','56')
        console.log(ldh);
        console.log(pcj)

2.在类中添加方法

// 给类添加方法!!!
// 不需要写function, 函数和函数之间不能加逗号!!!
      var that;
        class Person {
            constructor(name, age) {
                that = this;
                this.name = name;
                this.age = age;
            }
            // 给类添加方法!!!
            // 不需要写function, 函数和函数之间不能加逗号!!!
            run() {
                console.log("....")
            }

            jump() {
                console.log("....")
            }
        }

        var p1 = new Person("zhangsan", 18)
        

        var p2 = new Person("zhangsan", 18)
        p2.run()

3.类中实现继承

extends 继承!!!
class Son extends Father{}
super(x, y) 调用了父类中的构造函数!!!
加上static 那么这个属性或者方法就是类上面的
 class Father {
            constructor(x, y,z) {
                this.x = x;
                this.y = y;
                this.z = z;
            }
            sum() {
                console.log(this.x + this.y)
            }
        }

                // extends 继承!!!
        class Son extends Father{
            constructor(x, y) {
                super(x, y,z) // 调用了父类中的构造函数!!!
                // this.x = x;
                // this.y = y;
            }
            // static关键词是什么?如果加上static 那么这个属性或者方法就是类上面的
           sub() {
                console.log(this.x - this.y)
            }
        }

        var s1 = new Son(10, 5)
        // console.log(s1)
        s1.sum(); // 说明s1实例对象上已经有了这个sum函数!!!
        s1.sub();