javascript继承
一、对象冒充
function Parent(username){
this.username=username;
this.sayHello=function(){
alert(this.username);
}
}
function Child(username,password){
//这三行关键代码
this.method=Parent;
this.method(username);
delete this.method;
this.password=password;
this.sayWorld=function(){
alert(this.password);
}
}
二、call方法(call方法是function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会传递给函数中的this,从第二个参数开始,逐一赋值给函数中的参数)
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);
}
}
三、apply方法
function Parent(username){
this.username=username;
this.sayHello=function(){
alert(this.username);
}
}
function Child(username,password){
Parent.apply(this,new Array(username));
this.password=password;
this.sayWorld=function(){
alert(this.password);
}
}
四、原型链方法(无法给构造函数传参数)
function Parent(){
}
Parent.prototype.hello="hello";
Parent.prototype.sayHello=function(){
alert(this.hello);
}
function Child(){
}
Child.prototype=new Parent();
Child.prototype.world="world";
Child.prototype.sayWorld=function(){
alert(this.world);
}
五、混合方式(推荐)
function Parent(hello){
this.hello=hello;
}
Parent.prototype.sayHello=function(){
alert(this.hello);
}
function Child(hello,world){
Parent.call(this.hello);
this.world=world;
}
Child.prototype=new Parent();
Child.prototype.sayWorld=function(){
alert(this.world);
}