码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象

时间:2018-10-30 17:40:29      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:console   strong   获得   面向对象   对象   cal   函数   定义   str   

 

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

 


 

 

封装

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

  以代码为例,我们先建立一个构造函数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, 由于参数的不同, 导致不同的调用结果,这就实现了多态.

 

面向对象

标签:console   strong   获得   面向对象   对象   cal   函数   定义   str   

原文地址:https://www.cnblogs.com/dawnwill/p/9876861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!