zoukankan      html  css  js  c++  java
  • 面向对象

    面向对象的编程思想:根据需求,抽象出属性和方法,定义构造函数,然后实例化对象,通过对象调用属性和方法,完成相应的需求


    封装

    把抽象出来的属性和对方法组合在一起, 且属性值被保护在内部, 只有通过特定的方法进行改变和读取称为封装
    

      以代码为例,我们先建立一个构造函数Person,它有两个属性和一个方法

            // 封装
            function Person(name,age){
                this.name=name;
                this.age=age;
                this.play=function(){
                    console.log(this.name+'就喜欢蹦极!')
                }
            }
            let p1=new Person('jack',22);
            p1.play();    

      然后我们生成一个实例对象p1,并调用构造函数的play方法。

      p1这个对象并不知道play()这个方法是如何实现的, 但是仍然可以使用这个方法. 这其实就是封装

    2、继承

      

    可以让某个类型的对象获得另一个类型对象的属性和方法称为继承
    

     这里使用call()方法实现继承

            
        
        // 继承
        function Person(name,age){
                this.name=name;
                this.age=age;
                this.play=function(){
                    console.log(this.name+'就喜欢蹦极!')
                }
            }
            
            function Child(name,age,weight){
                Person.call(this,name,age);
                this.weight=weight;
            }
    
            let child1=new Child('jane',11,55);
            child1.play();    

    3、多态

    同一操作作用于不同的对象产生不同的执行结果, 这称为多态
    

     

            // 多态
                function Person(name) {
                this.name = name;
            }
    
            function Student(subject) {
                this.subject = subject;
                this.study = function () {
                    console.log(this.name + "在学习" + this.subject);
                }
            }
    
            function Teacher(subject) {
                this.subject = subject;
                this.study = function () {
                    console.log(this.name + "在学习" + this.subject);
                }
            }
    
            Student.prototype = new Person('john');
            Teacher.prototype = new Person('lucy');
    
            let stu = new Student('历史');
            let tea = new Teacher('教学');
            stu.study();
            tea.study();        
    对于同一函数doStudy, 由于参数的不同, 导致不同的调用结果,这就实现了多态.
  • 相关阅读:
    mysql性能分析工具
    vim使用大全
    Vue computed属性
    模板题 + KMP + 求最小循环节 --- HDU 3746 Cyclic Nacklace
    Greedy --- HNU 13320 Please, go first
    DFS --- HNU 13307 Galaxy collision
    HNU 13308 Help cupid
    Linux
    dp
    2015 Multi-University Training Contest 2 1006 Friends
  • 原文地址:https://www.cnblogs.com/dawnwill/p/9876861.html
Copyright © 2011-2022 走看看