构造函数的继承

原文地址: http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance.html

方式一: 通过call或apply方法,将父对象的构造函数绑定在子对象上。

     apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性.   call:和apply的意思一样,只不过是参数列表不一样.

function Animal(){
	this.species = "动物";
}
function Cat(name , color){
	Animal.apply(this , arguments);
	this.name = name ; 
	this.color = color ;
}

var cat1 = new Cat('毛' ,'黄色');
alert(cat1.species);

 

方式二:使用prototype属性

function Animal(){
		this.species = "动物";
	}
	function Cat(name , color){
		Animal.apply(this , arguments);
		this.name = name ; 
		this.color = color ;
	}
	Cat.prototype = new Animal();   //将Cat的prototype对象指向一个Animal的实例,相当于完全删除了prototype 对象原先的值,然后赋予一个新值
	Cat.prototype.constructor = Cat; //任何一个prototype对象都有一个constructor属性,指向它的构造函数。如果没有"Cat.prototype = new Animal();"这一行,Cat.prototype.constructor是指向Cat的;加了这一行以后,Cat.prototype.constructor指向Animal

	var cat1 = new Cat('毛' ,'黄色');
	alert(cat1.species);

 

 方式四:利用空对象作为中介

var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

F是空对象,所以几乎不占内存。这时,修改Cat的prototype对象,就不会影响到Animal的prototype对象。

 

posted @ 2014-10-16 15:34  vivi.wang  阅读(169)  评论(0编辑  收藏  举报