JavaScript学习之面向对象

面向对象

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

JavaScript的继承机制

在这里插入图片描述在这里插入图片描述
代码示例:

<script>
         //prototype
         function Person(name ,age){
    
    
            this.name = name;
            this.age = age;
            this.info = function (){
    
    
                document.write("姓名:"+this.name+"<br>");
                document.write("年龄:"+this.age+"<br>");
            }
        }
        var p1 = new Person("法外狂徒张三",29);
        p1.info();
        Person.prototype.walk = function(){
    
    
            document.write(this.name+"溜达"+"<br>");
        }
        document.writeln("<hr>");
        var  p2 = new Person("leegang" , 30);
        p2.info();
        document.writeln("<hr>");
        p2.walk();
        p1.walk();
     </script>

在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

构造器实现伪继承

在这里插入图片描述在这里插入图片描述

使用apply或者call实现伪继承

在这里插入图片描述
代码示例:

<script>
        //prototype
        function Person(name ,age){
    
    
           this.name = name;
           this.age = age;
           
       }
       Person.prototype.sayHello = function(){
    
    
             console.log(this.name+"正在打招呼");
       }
       var p1 = new Person("法外狂徒张三",29);
       p1.sayHello();
       function student(name,age,grade){
    
    
           Person.call(this,name,age);
           this.grade = grade;
       }
       student.prototype = new Person();
       student.prototype.intro = function(){
    
    
           console.log("%s是个学生,读%d年级",this.name,this.grade);
       }
       var stu = new student('李四',34,5);
       var stu2 = new student('王五',33,4);
       console.log(stu instanceof student);
       console.log(stu instanceof Person);
       stu.intro();
       stu2.intro();
       stu.sayHello();
       stu2.sayHello();
    </script>

在这里插入图片描述
在这里插入图片描述
使用call方法继承构造方法,使用prototype属性来继承类的其他方法。
继承代码示例:

script>
        function Animal (sex,age){
    
    
            this.sex = sex;
            this.age = age;
        }
        Animal.prototype.intro = function(){
    
    
            console.log("性别:"+this.sex+",年龄:"+this.age);
        }
        function Dog(kind,sex,age){
    
    
            this.kind = kind;
            Animal.call(this,sex,age);
        }
        Dog.prototype = new Animal();
        Dog.prototype.voice = function (){
    
    
            console.log(this.kind+"叫的声音是:汪汪汪");
        }
        function Cat(kind,sex,age){
    
    
            this.kind = kind;
            Animal.call(this,sex,age);
        }
        Cat.prototype = new Animal();
        Cat.prototype.voice = function (){
    
    
            console.log(this.kind+"叫的声音是:嗷嗷嗷");
        }
        var d = new Dog("哈士奇","公",12);
        d.intro();
        d.voice();
        var c = new Cat("波斯猫","母",5);
        c.intro();
        c.voice();
    </script>

在这里插入图片描述

创建对象

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Walker7143/article/details/105642303