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();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值