JavaScript 中的继承

JavaScript 没有“类”的概念,而是通过原型来实现继承。

这里推荐一下阮一峰的一系列文章。

JavaScript中实现继承的方式有多种,在此一一列举。

一,构造函数的继承:

方式一:通过prototype实现继承

function Person(name){
this.name=name;
}
function Student(info){
this.info=info;
}


Student.prototype=new Person('Jack');//将Student的prototype对象指向Person的实例
Student.prototype.constructor=Student;//在上一步中,由于改变了Student的prototypt的指向了Person,所以prototype的
                                      //constructor属性也指向了Person,所以要手动改回Student.prototype.constructor属性
var student=new Student("123");
student.name;//Jack


于是,student就具有了年龄这个属性。方式二:构造函数链(constructor chaining)

function Person(name){
this.name=name;
}
function Student(info){
  Person.apply(this,arguments);
 this.info=info;
}
var student=new('Jack','123');
方式三:直接继承prototype

function Person(){}
Person.prototype.name="sun";

Student.prototype=Person.prototype;

Student.prototype.constructor=Student;
var student=new Student("Jack","123");
注意:Person.prototypr和Student.prototype指向同一对象,一个修改则会影响到另一个

方式四:利用空对象

function extend(Child,Parent){
var F=function(){};
F.prototype=Person.prototype;
Student.prototype=new F();
Student.prototype.constructor=Student;
Child.uber=Parent.prototype
}
使用:
extend(Student,Person);
var student=new Student("Jack","123");
方式五:拷贝继承:

function Person(){}
Person.prototype.name="sun";
copy:
function extend2(Child,Parent){
var p=Parent.prototype;
varc=Child.prototype;
for (var i in p)
c[i]=p[i];
}
c.uber=p;
使用:
exteng2("Student","Parent");
var student=new Student("Jsck","123");




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值