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); //老明
3.call和applay繼承:
function teacher(name){ this.name=name; this.sayName=function(){ alert(this.name); } } function student(age){ teacher.call(this,"小明"); this.age=age; } var ss=new student("30"); ss.sayName();//小明 alert(ss.age);//30