日期:2014-05-16  浏览次数:20403 次

JavaScript面向对象的继承的几种方式

看了一些资料和视频,有五种方式实现继承,代码如下:

?

/**
 * 继承的五种方法
 * @author wangds
 *
 *
 * 1.call方法
 * call方法是Function对象中的方法,因此我们定义的每一个函数都拥有该方法。
 * 可以通过函数名来调用call方法,call方法的第一个参数会被传递函数中的this
 * 从第二个参数开始,逐一赋值给函数中的参数
 * @param {Object} username
 */
function Parent(username){
	this.username = username;
	this.sayHello = function(){
		alert(this.username);
	}
}

function Child(username, password){
	Parent.call(this,username);
	this.password = password;
	
	this.sayWorld = function(){
		alert(this.password);
	}
}

var parent = new Parent("wds");
var child = new Child("zzh","you amd me");

parent.sayHello();

child.sayWorld();
child.sayHello();

/**
 * 2.apply
 */
function ParentApply(username){
	this.username = username;
	this.sayHello = function(){
		alert("ParentApply.sayHello:" + this.username);
	}
}
function ChildApply(username, password){
	ParentApply.apply(this, new Array(username));
	this.password = password;
	
	this.sayWorld = function(){
		alert("ChildApply.sayWorld:" + this.password);
	}
}
var p = new ParentApply("wds");
var c = new ChildApply("zzh", "pass");
p.sayHello();

c.sayWorld();
c.sayHello();

/**
 * 3.原型链
 */
function ParentProto(){}

ParentProto.prototype.hello = "Wds Hello";
ParentProto.prototype.sayHello = function(){
	alert(this.hello);
}

function ChildProto(){}

ChildProto.prototype = new ParentProto();
ChildProto.prototype.world = "wrp World";
ChildProto.prototype.sayWorld = function(){
	alert(this.world);
}

var child = new ChildProto();
child.sayHello();
child.sayWorld();

/**
 * 4.混合式
 */
function ParentMix(hello){
	this.hello = hello;
}
ParentMix.prototype.sayHello = function(){
	alert(this.hello);
}

function ChildMix(hello, world){
	ParentMix.call(this, hello);
	this.world = world;
}
ChildMix.prototype.sayWorld = function(){
	alert(this.world);
}

var childMix = new Child("Hello Mix", "World Mix");
childMix.sayHello();
childMix.sayWorld();

/**
 * 5.对象冒充
 */
function ParentFirst(username){
	this.username = username;
	
	this.sayHello = function(){
		alert(this.username);
	}
}

function ChildFirst(username, password){
	this.method = ParentFirst;
	this.method(username);
	delete this.method;
	
	this.password = password;
	
	this.sayWorld = function(){
		alert(this.password);	
	}
}

var firstParent = new ParentFirst("first Parent");
var firstChild = new ChildFirst("firstChild","firstPassword");

firstParent.sayHello();

firstChild.sayHello();
firstChild.sayWorld();

?