var extend = function(subClass, baseClass){
var inheritance = function(){};
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
subClass.prototype.base = function(){
baseClass.apply(this, arguments);
}
};var Animal = function(name){
this.name = name;
}var Cat = function(name, age){
this.base(name);
this.age = age;
}var ColorCat = function(name, age, color){
this.base(name,age);
this.color = color;
}extend(Cat, Animal);
extend(ColorCat, Cat);var bluecat = new ColorCat("mical", 20, "blue"); // 溢出
var extend = function(subClass, baseClass){
var inheritance = function(){};
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance();
/*
subClass.prototype.base = function(){
baseClass.apply(this, arguments);
}
*/
subClass.base = baseClass;
};var Animal = function(name){
this.name = name;
}var Cat = function(name, age){
/*this.base(name);*/
Cat.base.call(this, name);
this.age = age;
}var ColorCat = function(name, age, color){
/*this.base(name,age);*/
ColorCat.base.call(this, name, age);
this.color = color;
}extend(Cat, Animal);
extend(ColorCat, Cat);var bluecat = new ColorCat("mical", 20, "blue"); // 溢出
alert(bluecat.name);
alert(bluecat.age);
alert(bluecat.color);
我擦~ 您这个程序够狠~ 害得我调了大半天。。
去掉这句
subClass.prototype.base = function(){
baseClass.apply(this, arguments);
}你可以在里面加个断点,或者firebug下面,加个console.log,这里无限次的调用。
我的 subClass.prototype.base = function(){
baseClass.apply(this, arguments);
}应该怎么改
无限递归的原因有二
1. 你无限次地调用ColorCat的base函数所导致的。
2. 导致你无线此调用base函数的原因是两个构造函数Cat和ColorCat都有this.base()这种调用,由于apply函数的错误使用,导致this的指向错误。从ColorCat类实例被创建的那一刻起,两个构造函数中this.base()的this指向一直都没变,都是指向ColorCat的实例。
程序执行的步骤如下:
1. 在执行代码 var bluecat = new ColorCat("mical", 20, "blue"); 的时候,解析器回去执行这个类的构造函数ColorCat2. 执行ColorCat构造函数,第一句执行的就是 this.base(name,age);
根据我们的extend函数缩执行的结果,我们的base函数会去执行这个代码:
baseClass.apply(this, arguments); 其中baseClass现在是Cat,而this现在是ColorCat的实例的引用(由于extend(ColorCat, Cat)这句代码所产生的结果)。3. 第2步执行的apply会把this应用到Cat构造函数上,这意味着现在构造函数Cat的函数体中所包含的所有的this都指向ColorCat的实例,然而Cat构造函数体中所执行的第一个句代码就是:
this.base(...);
根据上面的分析,这里的this显然是ColorCat的实例。所以它又返回去调用他自己! OK,无限调用的base函数的条件已经构成。 最后,报错了!!!
兄台. smile~~