1.对象冒充
function Parent(username){
this.username=username;
this.hello=function(){
console.log(this.username);
}
}
/*
1.用this.method作为临时属性,指向parent对象
2.执行this.method方法,执行Parent指的对象属性
3.销毁this.method属性,此时的child已经有了parent的属性和方法
*/
function Child(username,passsword){
this.method=Parent;
this.method(username);
delete this.method;
this.password=password;
this.word=function(){
console.log(this.password)
}
}
var parent=new Parent("abc");
var child=new Child("123","123");
parent.hello();
child.hello();
child.word();
2.call()方法实现继承
call方法是Function类中的方法
call方法的第一个参数的值赋值给类(即方法)中出现的this
call方法的第二个参数开始依次赋值给类(即方法)所接受的参数
function test(str){
console.log(this.name+" "+str);
}
var obj=new Object();
obj.name="doctor";
test.call(obj,'我是传入的str');
function Parent2(username){
this.username=username;
this.hello=function(){
console.log(this.username);
}
}
function Child2(username,password){
Parent2.call(this,username);
this.password=password;
this.word=function(){
console.log(this.password);
}
}
var parent2=new Parent("p1");
var child2=new Child2("C2","cpwd");
parent2.hello();
child2.hello();
child2.word();
3.apply()方法
apply方法接受2个参数,
A、第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this
B、第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数
function Parent3(username){
this.username=username;
this.hello=function(){
console.log(this.username);
}
}
function Child3(username,password){
/*
调用Parent的方法
*/
Parent3.apply(this,new Array(username));
this.password=password;
this.word=function(){
console.log(this.password);
}
}
var parent3=new Parent3('abc');
var child3=new Child3('def','123');
parent3.hello();
child3.hello();
child3.word();
4.原型链法
function Person(){
}
Person.prototype.hello="hello";
Person.prototype.sayHello=function(){
console.log(this.hello);
}
function Kid(){
}
Kid.prototype=new Person();
Kid.prototype.world="world";
Kid.prototype.sayWord=function(){
console.log(this.world);
}
var c=new Kid();
c.sayHello();
c.sayWord();
5.混合方式
function Parent(hello){
this.hello=hello;
}
Parent.prototype.sayHello=function(){
console.log(this.hello);
}
function Child(hello,word){
Parent.call(this,hello);//将父类的属性继承过来
this.word=word;
}
Child.prototype=new Parent();//将父类的方法继承过来
Child.prototype.sayWord=function(){
console.log(this.word);
}
var c=new Child("123","456");
c.sayWord();
c.sayHello();