1、原型赋值继承:直接将父类的一个实例赋给子类的原型,相当于将父类原型上的方法和属性以及挂在this上的方法和属性全部赋给了子类的原型。
function Person(name){ this.name=name; this.className="person" } Person.prototype.getClassName=function(){ console.log(this.className) } function Man(){ } Man.prototype = new Person(); var man = new Man('aa'); //传入的参数没被接收 console.log(man.name); // undefined console.log(man.className); //person console.log(man.getClassName()); //person console.log(man instanceof Person) //true console.log(man.constructor) // function Person(name){}
缺点:子类无法通过父类创建私有属性。
2、构造函数继承:只能继承父类构造函数中的实例属性,无法继承父类原型的属性和方法。
function Person(name){ this.name=name; this.className="person"; } Person.prototype.getClassName=function(){ console.log(this.className); } function Man(name){ Person.apply(this,arguments); } var man = new Man('justin'); console.log(man.name); // justin console.log(man.className); //person console.log(man.getClassName()); //报错 console.log(man instanceof Person); //false console.log(man instanceof Man); //true console.log(man.constructor); // function Man(name){}
3、组合继承:
function Person(name){ this.name=name || 'default name'; this.className="person"; } Person.prototype.getClassName=function(){ console.log(this.className); } function Man(name){ Person.apply(this,arguments); } Man.prototype = new Person(); var man = new Man('justin'); console.log(man.name); // justin console.log(man.className); //person console.log(man.getClassName()); //person console.log(man instanceof Person); //true console.log(man instanceof Man); //true console.log(man.constructor); // function Person(name){} console.log(Man.prototype); // Person{name: "default name", className: "person"} 原型中的name属性还是存在
4、寄生组合继承(实用):构造函数属性继承,父类原型继承。
function Person(name){ this.name=name; this.className="person" ; } Person.prototype.getClassName=function(){ console.log(this.className); } function Man(name){ Person.apply(this,arguments); } Man.prototype = Object.create(Person.prototype); Man.prototype.constructor = Man; var man = new Man('justin'); console.log(man.name); // justin console.log(man.className); //person console.log(man.getClassName()); //person console.log(man instanceof Person); //true console.log(man instanceof Man); //true console.log(man.constructor); // function Man(name){} console.log(Man.prototype); // Person{}