JavaScript中的继承
最近看Sencha的源码被那4万多行代码震慑了。
里面使用了不少继承,我也忘的差不多了,这里权当复习一下。
1.对象冒充
function magician(name,skill){ this.name = name; this.skill = skill; this.perform = function(){ alert(this.name+":"+this.skill+"!!!"); }}function magicgirl(name,skill,age){ this.newMethod = magician; this.newMethod(name,skill); delete this.newMethod;//删除该指针 this.age = age; this.performMore = function(){ alert("A maigc girl only "+this.age+" years old!"); }}var me = new magician("Young","fireball");var sister = new magicgirl("Nina","lightning",16);me.perform();sister.perform();sister.performMore();function magicgirl(name,skill,age){ this.newMethod = girl; //假设有一girl类 this.newMethod(name); delete this.newMethod; this.newMethod = magician; this.newMethod(name,skill); delete this.newMethod; this.age = age; this.performMore = function(){ alert("A maigc girl only "+this.age+" years old!"); }}function magicgirl(name,skill,age){ //this.newMethod = magician; //this.newMethod(name,skill); //delete this.newMethod; magician.call(this,name,skill); this.age = age; this.performMore = function(){ alert("A maigc girl only "+this.age+" years old!"); }}function magicgirl(name,skill,age){ //this.newMethod = magician; //this.newMethod(name,skill); //delete this.newMethod; //magician.call(this,name,skill); magician.apply(this,new Array(name,skill)); this.age = age; this.performMore = function(){ alert("A maigc girl only "+this.age+" years old!"); }}function magician(){}magician.prototype.name = "";magician.prototype.skill = "";magician.prototype.perform = function(){ alert(this.name+":"+this.skill+"!!!");}function magicgirl(){}magicgirl.prototype = new magician();magicgirl.prototype.age = "";magicgirl.prototype.performMore = function(){ alert("A maigc girl only "+this.age+" years old!")}var me = new magician();var sister = new magicgirl();me.name = "Young";me.skill = "fireball";sister.name = "Nina";sister.skill = "lightning";sister.age = 16;me.perform();sister.perform();sister.performMore();function magician(name,skill){ this.name = name; this.skill = skill;}magician.prototype.perform = function(){ alert(this.name+":"+this.skill+"!!!");}function magicgirl(name,skill,age){ magician.call(this,name,skill); this.age = age;}magicgirl.prototype = new magician();magicgirl.prototype.performMore = function(){ alert("A maigc girl only "+this.age+" years old!")}var me = new magician("Young","fireball");var sister = new magicgirl("Nina","lightning",16);me.perform();sister.perform();sister.performMore();