首页 > 编程语言 > 详细

Javascript高级程序设计--读书笔记之面向对象(二)

时间:2019-04-06 22:59:38      阅读:147      评论:0      收藏:0      [点我收藏+]

 

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

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)
}

 

Javascript高级程序设计--读书笔记之面向对象(二)

原文:https://www.cnblogs.com/Qqqing/p/10663117.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!