1.原型链继承:
functionBook (name,author){
this.name=name;
this.author=author;
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){}
JavaScript.prototype=newBook("JavaScript","Nicholas");
varjs1=newJavaScript();
varjs2=newJavaScript();
js1.tell();
js2.tell();
可以发现,原型链继承有一个问题,那就是父类中的私有属性,会因为父类作为子类原型构建原型链,使得子类所有实例所共享。当我们通过一个实例修改共享属性时,其他实例也将受到影响:
functionBook (name,author){
this.name=name;
this.author=[author];
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){}
JavaScript.prototype=newBook("JavaScript","Nicholas");
varjs1=newJavaScript();
varjs2=newJavaScript();
js1.author.push("C.Zakas");
js2.tell();
但是当你直接为实例中属性赋值时,是在实例中重新定义了一个对应属性,而不是在修改原型中属性:
functionBook (name,author){
this.name=name;
this.author=author;
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){}
JavaScript.prototype=newBook("JavaScript","Nicholas");
varjs1=newJavaScript();
varjs2=newJavaScript();
js1.author="C.Zakas";
//并不是js1没有影响js2,而是在js1中创建了新author属性
console.log(js1.hasOwnProperty("author"));//true
console.log(js2.hasOwnProperty("author"));//false
js1.tell();//Book:JavaScript Author:C.Zakas
js2.tell()
2.构造函数继承:
functionBook (name,author){
this.name=name;
this.author=author;
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){
Book.apply(this,arguments);
}
varjs1=newJavaScript("JavaScript","Nicholas");
varjs2=newJavaScript("JavaScriopt","C.Zakas");
console.log("js1:"+js1.author+" js2:"+js2.author);//js1:Nicholas js2:C.Zakas
js1.tell();//Uncaught TypeError: js1.tell is not a function
js2.tell();//Uncaught TypeError: js2.tell is not a function
构造函数继承,可以使每个子类实例有一份自己的属性,但是无法找到父类原型中的函数。
3.组合继承:
functionBook (name,author){
this.name=name;
this.author=author;
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){
Book.apply(this,arguments);
}
JavaScript.prototype=newBook();
varjs1=newJavaScript("JavaScript","Nicholas");
varjs2=newJavaScript("JavaScriopt","C.Zakas");
console.log("js1:"+js1.author+" js2:"+js2.author);//js1:Nicholas js2:C.Zakas
js1.tell();//Book:JavaScript Author:Nicholas
js2.tell();
组合继承使得每个子类实例,既可以保存一份自己的属性,又可以共享同一个函数。
4.寄生组合继承:
functionBook (name,author){
this.name=name;
this.author=author;
}
Book.prototype.tell=function(){console.log("Book:"+this.name+" Author:"+this.author);};
functionJavaScript(){
Book.apply(this,arguments);
}
JavaScript.prototype=Object.create(Book.prototype);
JavaScript.prototype.constructor=JavaScript;
varjs1=newJavaScript("JavaScript","Nicholas");
varjs2=newJavaScript("JavaScriopt","C.Zakas");
console.log("js1:"+js1.author+" js2:"+js2.author);//js1:Nicholas js2:C.Zakas
js1.tell();
js2.tell();
console.log(js1.tell===js2.tell);