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的
var student=new Student("123");//constructor属性也指向了Person,所以要手动改回Student.prototype.constructor属性
student.name;//Jack
于是,student就具有了年龄这个属性。方式二:构造函数链(constructor chaining)方式三:直接继承prototypefunction Person(name){ this.name=name; } function Student(info){ Person.apply(this,arguments); this.info=info; } var student=new('Jack','123');
注意:Person.prototypr和Student.prototype指向同一对象,一个修改则会影响到另一个function Person(){} Person.prototype.name="sun"; Student.prototype=Person.prototype; Student.prototype.constructor=Student; var student=new Student("Jack","123");
方式四:利用空对象
方式五:拷贝继承: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");