javascript继承方式

本文详细介绍了JavaScript中五种实现继承的方法:对象冒充、call方法、apply方法、原型链及混合方式,并对比了它们的特点和适用场景。
[b]1.对象冒充[/b]
[quote]

function Parent(username){
this.username = username;
this.sayHello = function(){
alert("hello,"+this.username);
}
}
function Child(username,password){
//三行重要代码
this.method = Parent;
this.method(username);
delete this.method;
this.password = password;
this.sayWorld = function(){
alert("world,"+this.password);
}
}

var parent = new Parent("wlh");
var child = new Child("wlh_child","111111");
parent.sayHello();

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

[/quote]
[b]2.call方法方式:[/b]call方法是Function对象中的一个方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第二个参数开始,逐个赋值给函数中的参数。
[u]1)call方法使用方式:[/u]
[quote]

function test(str,str2){
alert(this.name + "," +str + "," +str2);
}
var object = new Object();
object.name = "wlh";
//相当于调用了test函数
test.call(object,"wlhs");//将object赋给了this

[/quote]
结果:
wlh,wlhs,undefined
[u]2)call方法继承[/u]
function Parent(username){  
this.username = username;
this.sayHello = function(){
alert("hello,"+this.username);
}
}
function Child(username,password){
Parent.call(this,username);
this.password = password;
this.sayWorld = function(){
alert("world,"+this.password);
}
}
var parent = new Parent("wlh");
var child = new Child("wlh_child","111111");
parent.sayHello();

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

[b]3.apply方法方式[/b]

function Parent(username){
this.username = username;
this.sayHello = function(){
alert("hello,"+this.username);
}
}
function Child(username,password){
Parent.apply(this,new Array(username));
this.password = password;
this.sayWorld = function(){
alert("world,"+this.password);
}
}
var parent = new Parent("wlh");
var child = new Child("wlh_child","111111");
parent.sayHello();

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

[b]4.原型链方式(prototype chain):[/b]

function Parent(){
}

Parent.prototype.username = "wlh";
Parent.prototype.getUsername = function(){
alert(this.username);
}

function Child(){
}

Child.prototype = new Parent();
Child.prototype.password = "111111";
Child.prototype.getPassword = function(){
alert(this.password);
}

var child = new Child();
child.getUsername();
child.getPassword();

[b]缺点:无法实现参数的传递[/b]
[b]5.混合方式(推荐使用该方式)[/b]

function Parent(username){
this.username = username;
}

Parent.prototype.getUsername = function(){
alert(this.username);
}

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

Child.prototype = new Parent();
Child.prototype.getPassword = function(){
alert(this.password);
}

var child = new Child("wlh","111111");
child.getUsername();
child.getPassword();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值