类式继承
类式继承是在函数对象内调用父类的构造函数,使得自身获得父类的方法和属性。call和apply方法为类式继承提供了支持。通过改变this的作用环境,使得子类本身具有父类的各种属性。
var father=function(){ this.age=22; this.say=function(){ alert('hello i am '+this.name+' and i am '+this.age+'years old'); } } var child=function(){ this.name='wyy'; father.call(this); } var man=new child(); man.say();
原型继承
原型继承在开发中经常用到。它有别于类继承是因为继承不在对象本身,而在对象的原型上prototype。把父类的对象赋值给子类构造函数的原型,这样子类的对象就可以访问到父类以及父类构造函数的prototype中的属性。 这种方法的原型继承图如下:
var Parent = function(){ this.name = 'parent' ; } ; Parent.prototype.getName = function(){ return this.name ; } ; Parent.prototype.obj = {a : 1} ; var Child = function(){ this.name = 'child' ; } ; Child.prototype = new Parent() ; var parent = new Parent() ; var child = new Child() ; console.log(parent.getName()) ; //parent console.log(child.getName()) ; //child