js对象继承
一般继承时出现的问题
function people(name,sex){ this.name=name; this.sex=sex; } people.prototype.showname=function(){ alert(this.name); } function student(name,sex,job){ people.call(this,name,sex); this.job=job; } student.prototype = people.prototype;//对象赋给对象,就会出现对象的引用,如果子类原型添加一个方法,父类就会受影响 var p1=new people('jack',32); var s1=new student('jenny',24,'student'); console.log(p1); console.log(s1);
拷贝继承:通用型的,有new或无new的时候都可以
function people(name,sex){ this.name=name; this.sex=sex; } people.prototype.showname=function(){ alert(this.name); } function student(name,sex,job){ people.call(this,name,sex);//属性继承:调用父类的构造函数 this.job=job; } extend(student.prototype,people.prototype);//拷贝继承,利用for in 实现方法的继承 student.prototype.showjob=function(){ alert(); } function extend(obj1,obj2){ for (var attr in obj2) { obj1[attr]=obj2[attr]; } } var p1=new people('jack',32); var s1=new student('jenny',24,'student'); console.log(p1); console.log(s1);
类式继承:带new构造函数
function Aaa(){ this.name=[2,3,4]; } Aaa.prototype.showname=function(){ alert(this.name); } function Bbb(){ Aaa.call(this); } var F= function(){}; F.prototype=Aaa.prototype; Bbb.prototype=new F(); Bbb.prototype.constructor=Bbb; var b1=new Bbb(); b1.name.push(5); var b2=new Bbb(); alert(b2.showname);
原型继承:无new的对象
var a = {name: '小明'}; var b = clone(a);
b.name='小青'; alert(a.name); function clone(obj){ var F =function(){}; F.prototype=obj; return new F(); }