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对象上。

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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属性被更改了)

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

  

posted @   yangkangkang  阅读(249)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示