zoukankan      html  css  js  c++  java
  • JS中的继承总结

    面向对象特性:封装,继承,多态

    继承,类与类之间的关系,面向对象的语言的继承是为了多态服务的,
    js不是面向对象的语言,但是可以模拟面向对象.模拟继承.为了节省内存空间

    继承:

    原型作用: 数据共享 ,目的是:为了节省内存空间,
    原型作用: 继承 目的是:为了节省内存空间

    方式一:原型继承:改变原型的指向

        function Person(age) {
            this.age = age;
        }
        Person.prototype.eat = function() {
            console.log("人正在吃东西");
        }
    
        function Student(sex) {
            this.sex = sex;
        }
        Student.prototype = new Person(12);
        Student.prototype.study = function() {
            console.log("学生在学数学");
        }
        var stu = new Student("女");
        stu.eat();
        stu.study();

    方式二:借用构造函数继承:主要解决属性的问题

         function Person(name, age) {
                this.name = name;
                this.age = age;
            }
            Person.prototype.sayHi = function() {
                console.log("say,hi");
            }
    
            function Student(name, age, score) {
                Person.call(this, name, age, score);
                this.score = score;
            }
            var stu = new Student("小白", 20, 130);
            var stu2 = new Student("小乐", 23, 110);
            console.log(stu.name + stu.age + "==" + stu.score);
            console.log(stu2.name + stu2.age + "==" + stu2.score);
            stu.sayHi(); /* call方式不能继承父级的方法 */

    方式三:组合继承:原型继承+借用构造函数继承

    既能解决属性问题,又能解决方法问题

            function Animate(style, sex) {
                this.style = style;
                this.sex = sex;
            }
            Animate.prototype.sleep = function() {
                console.log("要去睡觉了");
            }
    
            function Dog(style, sex, name) {
                Animate.call(this, style, sex);
                this.name = name;
            }
            Dog.prototype = new Animate();
            var dog = new Dog("藏獒", "公的", "大熊");
            console.log(dog.style, dog.sex, dog.name);
            dog.sleep();    


    方式四:拷贝继承:就是把对象中需要共享的属性或者犯法,直接遍历的方式复制到另一个对象中

            function Person() {}
            Person.prototype = {
                // constructor: Person,
                name: "小白",
                sex: "女",
                age: 21,
                sleep: function() {
                    console.log("可以睡觉了");
                }
            }
            var stu = {};
            for (var key in Person.prototype) {
                stu[key] = Person.prototype[key];
            }
            console.log(stu)        
  • 相关阅读:
    Lambada. 计算和
    adb server version (31) doesn't match this client (39) 解决方案
    python爬虫beautifulsoup4系列2
    python爬虫beautifulsoup4系列1
    利用Python攻破12306的最后一道防线
    python自动化17-JS处理滚动条
    python多线程
    python接口自动化2-发送post请求
    python接口自动化1-发送get请求 前言
    jenkens其实是代码上传工具
  • 原文地址:https://www.cnblogs.com/qtbb/p/12582624.html
Copyright © 2011-2022 走看看