• javascript的继承方法


    一、构造函数继承

      该方法最简单,使用call或者apply方法,将父对象的构造函数绑定到子对象上。

    function Parent(name){
        this.name = name;
        this.color = ['red','green'];
            this.getInfo = function(){
            alert(this.name + '喜欢的颜色:'+ this.color)
        }
    }
    
    function Child(name){
        Parent.call(this,name);
    }
    
    var child1 = new Child('张三');
    child1.color.push('black');
    child1.getInfo();// 张三喜欢的颜色: red,green,black
    var child2 = new Child('李四');
    child2.getInfo();    // 李四喜欢的颜色: red,green

    这样实现有一个弊端,就是每new一次,实例对象的属性和方法都会开辟内存空间,比较浪费内存,缺乏效率。

    为了解决内存消耗问题,下面介绍一下原型链继承

    二、原型链继承

      我们知道每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有方法和属性都会被构造函数的实例继承。所以我们可以把不变的属性和方法定义在prototype对象上。

      

    function Parent(name){
    	this.name = name;
    	this.color = ['red','green'];
    }
    //不变的属性或方法定义在prototype上,prototype对象上的方法是共享的, 每次new Parent()时不需要重新开辟内存空间
    Parent.prototype.getInfo = function(){
    	alert(this.name + '喜欢的颜色:'+ this.color)
    }
    function Child(name){
    }
    Child.prototype = new Parent();
    		
    var child1 = new Child('张三');
    
    child1.color.push('black');  //此操作会改变Parent构造函数的color属性 color值变成[red,green,black] 
    
    child1.getInfo(); //undefined喜欢的颜色 : red,green,black 
    
    var child2 = new Child('李四'); 
    
    child2.getInfo();//undefined喜欢的颜色 : red,green,black ,
    

      

    原型链继承存虽然解决了构造函数消耗内存的问题,但是这种继承方式存在两个问题:

      问题1: 创建子类型的实例时,无法向父类构造函数传递参数(例子中:Childh的name参数无法传给Parent中)。

      问题2:如果构造行数的属性是引用类型,并且集成后改变了其值,则父构造函数中得值会被更改(例子中的color属性被更改了)

    三、混合继承(构造函数和原型结合方式)

      借鉴以上两种方式的优缺点,采用构造函数和原型结合方式

    function Parent(name){
    	this.name = name;
    	this.color = ['red','green'];
    }
    //不变的属性或方法定义在prototype上,prototype对象上的方法是共享的, 每次new Parent()时不需要重新开辟内存空间
    Parent.prototype.getInfo = function(){
    	alert(this.name + '喜欢的颜色:'+ this.color)
    }
    function Child(name){
    	//通过call或者apply实现继承Parent,相当于重新创建了Parent属性的副本
    	//Parent中的属性会copy出一份,重新开辟内存空间
    	Parent.call(this,name); 
    	//Parent.apply(this,[name]);
    }
    Child.prototype = new Parent();
    		
    var child1 = new Child('张三');
    child1.color.push('black');
    child1.getInfo(); //张三喜欢的颜色 : red,green,black
    var child2 = new Child('李四');
    child2.getInfo();//李四喜欢的颜色 : red,green
    

      

  • 相关阅读:
    http状态码
    Django基础篇(二)
    Django基础篇
    mysql进阶
    mysql数据库的基本操作
    JavaScript
    分布式原理之RPC框架
    Java实现本地缓存
    模版方法模式:封装算法 && 迭代器与组合模式:管理良好的集合
    分布式高并发系统设计与分析
  • 原文地址:https://www.cnblogs.com/yangkangkang/p/7569977.html
Copyright © 2020-2023  润新知