日期:2014-05-16  浏览次数:20414 次

javascript代码复用--继承

由于javascript没有类的概念,因此无法通过接口继承,只能通过实现继承。实现继承是继承实际的方法,javascript中主要是依靠原型链要实现。

原型链继承

原型链继承是基本的继承模式,其本质是重写原型对象,使其为新对象的实例。代码实现如下:

复制代码
function Person(){

    this.name = "default";

    var temp = "temp";

}

Person.prototype.age=0;

Person.prototype.getName = function(){

    return this.name;

}

Person.prototype.getAge = function(){

    return this.age;

}

console.log(Person.prototype.age);//0

console.log(Person.age);//undefined

console.log(Person.prototype.name);//undefined

console.log(Person.name);//Person, if other property, should be undefined

function Student(){

    this.type = "student";

}

//inheritance

Student.prototype = new Person();

console.log(Student.prototype.constructor);//Person(){}

console.log(Student.prototype.name);//default

Student.prototype.constructor = Student;

var student1 = new Student();

console.log(student1.getName());//default

console.log(student1.name);//default

console.log(student1.getAge());//0

console.log(student1.age);//0

console.log(student1.__proto__.age);//0

console.log(student1.temp);//undefined

console.log(student1 instanceof Object);//true