1.原型链继承:
function teacher(name){ this.name = name; } teacher.prototype.sayName = function(){ alert(this.name); } function student(name){ this.name = name; }
student.prototype = new teacher() var student1 = new student("xiaolan"); student1.sayName(); // name is xiaolan
2.组合式继承:
function Person (name) { this.name = name; }; Person.prototype.getName = function () { return this.name; }; function Parent (age) { Person.call(this,'老明'); //这一步很关键 this.age = age; }; Parent.prototype = new Person('老明'); //这一步也很关键 var result = new Parent(24); console.log(result.name); //老明 console.log(result.getName()); //老明 console.log(result.age); //24 var result1 = new Parent(25); //通过借用构造函数都有自己的属性,通过原型享用公共的方法 console.log(result1.name); //老明