Fork me on GitHub

JavaScript继承

拷贝继承: 通用型的 有new或无new的时候都可以
类式继承: new构造函数
原型继承: 无new的对象

拷贝继承

function CreatePerson(name,sex){   //父类
this.name = name;
this.sex = sex;
}
CreatePerson.prototype.showName = function(){
alert( this.name );
};

var p1 = new CreatePerson('小明','男');
//p1.showName();


function CreateStar(name,sex,job){ //子类
CreatePerson.call(this,name,sex);
this.job = job;
}

//CreateStar.prototype = CreatePerson.prototype;

extend( CreateStar.prototype , CreatePerson.prototype );

CreateStar.prototype.showJob = function(){};

var p2 = new CreateStar('黄晓明','男','演员');

p2.showName();

function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}

类式继承

function Aaa(){   //父类
this.name = [1,2,3];
}

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.showName();
//alert( b1.name );
//alert( b1.constructor );
b1.name.push(4);

var b2 = new Bbb();

alert(b2.name);

原型继承

function Parent(){
this.lastName = 'James';
}

function Child(){
this.age = 12;
}
Child.prototype = new Parent();

var test = new Child();
alert(test.age);
alert(test.lastName);