第一种模式:
function Person(){
}
Person.prototype.say=function(){
alert('hello');
}
var person=new Person();
person.say();//hello
根据第一种模式说一下继承的实现:
function Person(){
}
Person.prototype.say=function(){
alert('hello');
}
function Man(){}
Man.prototype=new Person()
var man=new Man();
man.say(); //hello
第二种模式:
function Person(){
var _this={};//创建一个空的对象
_this.say=function(){alert('hello')};
return _this;
}
function person=new Person();
person.say();//hello
第二种模式的继承:
function Person(){
var _this={};//创建一个空的对象
_this.say=function(){alert('hello')};
return _this;
}
function Man(){
var _this=new Person();
return _this;
}
var a=new Man();
a.say();//hello
本文作者:罗坚元
本文介绍了JavaScript中通过原型链实现的两种不同类型的继承方式。第一种是基于构造函数的继承,通过修改子类的原型对象指向父类的一个实例来实现方法的共享;第二种则是基于对象的继承,直接创建一个父类的实例并返回,从而让子类继承其属性和方法。

被折叠的 条评论
为什么被折叠?



