js中继承的几种用法总结(apply,call,prototype)—-记录学习
//父类构造函数Parent、子类构造函数Child(以下均是如此)
/**
*
*1.使用对象冒充实现继承(该种实现方式能够实现多继承)
实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过thiskeyword给全部的属性和方法赋值
*/
function Parent1(firstname){
this.fname = firstname;
this.age = 30;
this.sayAge = function (){
console.log("47---"+this.age);
console.log("48---"+this.fname);
}
}
function Child1(firstname){
this.parent = Parent1;//让父类的构造函数成为子类的方法
//console.log(this.parent);
this.parent(firstname);//然后调用该子类的方法,通过thiskeyword给全部的属性和方法赋值
delete this.parent1;
this.saySomeThing = function (){
console.log("57---"+this.fname);
this.sayAge();
}
//console.log(this);
}
var mychild1 = new Child1('li');
mychild1.saySomeThing();// 47---30 48---li
/*
* 2、用call方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链,则採用混合模式)
实现原理:改变函数内部的函数上下文this,使它指向传入函数的详细对象
*
*/
function Parent2(firstname){
this.fname = firstname;
this.age = 32;
this.sayAge = function (){
console.log("74---"+this.age);
}
}
function Child2(firstname){
this.saySomeThing = function(){
console.log("79---"+this.fname);
this.sayAge();
}
this.getName = function(){
return firstname
}
}
var mychild2 = new Child2('jingaier');
Parent2.call(mychild2,mychild2.getName());
mychild2.saySomeThing();//79---jingaier 74---32
/**
* 3、用Apply方法改变函数上下文实现继承(该种方式不能继承原型链,若想继承原型链。则採用混合模式)
实现原理:改变函数内部的函数上下文this,使它指向传入函数的详细对象
同call 区别就是传参不一样
* */
function Parent3(firstname){
this.fname = firstname;
this.age = 34;
this.sayAge = function(){
console.log("98---"+this.age);
}
}
function Child3(firstname){
this.saySomeThing = function (){
console.log("103---"+this.fname);
this.sayAge();
}
this.getName = function(){
return firstname
}
}
var mychild3 = new Child3('Young');
Parent3.apply(mychild3,[mychild3.getName()]);
mychild3.saySomeThing();//103---Young 98---34
/**
* 4、用原型链的方式实现继承
实现原理:使子类原型对象指向父类的实例以实现继承,即重写类的原型,弊端是不能直接实现多继承
* */
function Parent4(){
this.sayAge = function(){
console.log(this.age);
}
}
Parent4.prototype.method = function(){
console.log(this.age+'---'+this.fname);
}
function Child4(firstname){
this.fname = firstname;
this.age = 36;
this.saySomeThing = function(){
console.log(this.fname);
this.sayAge()
this.method();
}
}
Child4.prototype = new Parent4();
var mychild4 = new Child4('张');
mychild4.saySomeThing();//张 36 36---张
/**
* 用混合模式实现继承
* */
function Parent5(){
this.sayAge = function(){
console.log(this.age);
}
}
Parent5.prototype.method = function(){
console.log(this.age+'---'+this.fname);
}
function Child5(firstname){
Parent5.call(this);
this.fname = firstname;
this.age = 40;
this.saySomeThing = function (){
console.log(this.fname);
this.sayAge();
this.method();
}
}
Child5.prototype = new Parent5();
var mychild5 = new Child5('李');
mychild5.saySomeThing();//李 40 40---李