实现原理:在子类的构造函数中调用父类的构造函数。app
function Parent(name){ this.name = name; this.age = 40; this.sayName = function(){ console.log(this.name); } this.sayAge = function(){ console.log(this.age); } } function Child(name){ this.parent = Parent; this.parent(name); delete this.parent; this.saySomething = function(){ console.log(this.name); this.sayAge(); } } var child = new Child('Lee'); child.saySomething(); //Lee //40
实现原理:使用call方法改变函数上下文this指向,使之传入具体的函数对象。函数
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); } } function Child(name){ Parent.call(this,name); } var child = new Child('Mike'); child.say();//Mike40
实现原理:使用apply方法改变函数上下文this指向,使之传入具体的函数对象。this
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); } } function Child(name){ Parent.apply(this,[name]); //Parent.apply(this,arguments); 效果同上 } var child = new Child('Wade'); child.say();//wade40
实现原理:子类的原型对象指向父类的实例,即重写类的原型。prototype
function Parent(name){ this.name = name; this.say = function(){ console.log(this.name +' '+ this.age); } } function Child(age){ this.age = age; this.saySomething = function(){ console.log(this.name); } } Child.prototype = new Parent('petter'); var child = new Child(20); child.say();//petter 20
实现原理:使用原型链实现对原型属性和方法的继承,而经过借用构造函数来实现对实例属性的继承。code
function Parent(age){ this.name = 'petter'; this.age = age; } Parent.prototype.say = function(){ return this.name + ' ' + this.age; } function Child(age){ Parent.call(this,age); //Parent.apply(this,[age]); this.age = age; } Child.prototype = new Parent(); var child = new Child(21); child.say();//petter 21
实现原理:经过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的混合继承的缺点对象
function Animal(name){ this.name = name; this.sleep = function(){ console.log(this.name + 'is sleeping'); } } function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){ // 建立一个没有实例方法的类 var Super = function(){}; Super.prototype = Animal.prototype; //将实例做为子类的原型 Cat.prototype = new Super(); })(); // Test Code var cat = new Cat(); console.log(cat.name);//Tom console.log(cat.sleep());//Tom is sleeping console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); //true
因为此篇中有涉及原型链和Call、Apply, 后面会写关于此知识点的文章。继承