首页 > 编程语言 > 详细

javascript的继承方法

时间:2017-09-21 19:09:16      阅读:227      评论:0      收藏:0      [点我收藏+]

一、构造函数继承

  该方法最简单,使用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

  

javascript的继承方法

原文:http://www.cnblogs.com/yangkangkang/p/7569977.html

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