js继承
JS继承
(1)构造函数法
function Parent(){ this.name = "parentname"; } function Child(age,address){ Parent.call(this,arguments); this.age = age; this.address = address; } var child = new Child(); console.log(child.name);
(2) 原型继承法
function Parent(){ this.name = "parentname"; } function Child(age,address){ this.age = age; this.address = address; } Child.prototype = new Parent();//缺点是如果Parent比较大会浪费内存 var child = new Child(); console.log(child.name);//parentname
(3)直接继承prototype
function Parent(name){ this.name = name; } Parent.prototype.name = "prototypename"; function Child(age,address){ Parent.call(this,"childname");//继承父类中的属性 this.age = age; this.address = address; } Child.prototype = Parent.prototype;//缺点是Child和Parent的原型都指向了同一个对象,那么对任何一个的修改都会影响另一个 var child = new Child(); console.log(child.name);//childname
(4)利用空对象做为中介
function Parent(){ this.name = "parentname"; } function Child(age,address){ this.age = age; this.address = address; } var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; var child = new Child(); console.log(child.name);
上述抽象成方法如下:
function extend(child,parent){ var F = new Function(); F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; child.uber = parent.prototype.constructor; } function Parent(){ this.name = "parentname"; } function Child(age,address){ Child.uber.call(this,arguments); this.age = age; this.address = address; } extend(Child,Parent); var child = new Child(); console.log(child.name);
(5) 拷贝继承
function Parent(){ this.name = "parentname"; } Parent.prototype.getName=function(){ alert("prototypename"); }; function Child(age,address){ this.age = age; this.address = address; } function extend2(child,parent){//拷贝原型中的属性 var P = parent.prototype; var C = child.prototype; for (var i in P){ C[i] = P[i]; } C.uber = P; } extend2(Child,Parent); var child = new Child(); console.log(child.getName()); console.log(child.name);//underfinded