zoukankan      html  css  js  c++  java
  • Javascript高级程序设计--读书笔记之面向对象(二)

    前面讲了面向对象的封装,这章我们就来说一说继承

    1.原型链

    实现原型链有一种基本模式,其代码大概如下

    <script>
        function SuperType(){
            this.property = true
        }
        SuperType.prototype.getSuperValue = function(){
            return this.property;
        }
        function SubType(){
            this.subproperty = false
        }
        //继承了 SuperType
        SubType.prototype = new SuperType()
        SuperType.prototype.getSubValue = function(){
            return this.subproperty
        }
        var instance = new SubType()
        alert(instance.getSuperValue())   /true
    </script>

    以上代码定义了两个类型,SuperType 和SubType 每个类型分别有一个属性和方法,SubType继承了SuperType,实现的本质是重写原型对象

    原型链虽然很强大,可以用它来实现继承,但是也存在一些问题,引用类型的值会被的原型属性会被所有实例共享,通过下面代码说明问题

        //原型链的问题
        function SuperType(){
            this.colors = ["red", "blue", "green"]
        }
        function SubType(){}
        //继承了SuperType
        SubType.prototype = new SuperType()
        var instance1 = new SubType()
        instance1.colors.push("black")
        alert(instance1.colors)   //"red", "blue", "green","black"
        var instance2 = new SubType()
        alert(instance2.colors)   //"red", "blue", "green","black"

      2.组合继承

    function SuperType(name){
        this.name = name;
        this.colors = ['red', 'blue', 'green'];
    }
    SuperType.prototype.sayName = function(){
        alert(this.name);
    }
    function SubType( name, age){
        //继承属性
        SuperType.call(this, name)
        this.age= age
    } 
    //继承方法
    SubType.prototype = new SuperType()
    SubType.prototype.constructor = SubType
    SubType.prototype.sayAge = function(){
        alert(this.age)
    }

  • 相关阅读:
    MySql基础教程(三)——查询训练
    MySql基础教程(二)
    MySql基础教程(一)
    解决Eclipse闪退问题的方法总结
    MySQL图形工具 MySQL GUI Tools的安装使用方法
    MySql5.6版修改用户登录密码
    Windows下MySQL解压版的配置
    js 数组容易弄混的那些方法
    如何使CSS--better(系列二)
    如何使CSS--better(系列一)
  • 原文地址:https://www.cnblogs.com/Qqqing/p/10663117.html
Copyright © 2011-2022 走看看