日期:2014-05-16  浏览次数:20316 次

js问题,菜鸟求解答
代码一:
<script>
function Animal() { }
Animal.prototype.species = "Animal";
function Cat(name, color) {
  this.name = name;
  this.color = color;
}
var F = function () { };//不同点
F.prototype = Animal.prototype;
Cat.prototype = new F();//不同点
Cat.prototype.constructor = Cat;
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);//Animal
</script>
代码二:
<script>
function Animal() { }
Animal.prototype.species = "Animal";
function Cat(name, color) {
  this.name = name;
  this.color = color;
}
 function F() { };//不同点
F.prototype = Animal.prototype;
Cat.prototype = F.prototype;//不同点
Cat.prototype.constructor = Cat;
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);//Animal
</script>
两段代码结果都一样。
求教,这两段代码运行时,其内存与对象是否存在区别。
或者说这两段代码的本质区别是什么?

------解决方案--------------------
代码一:
<script>
function Animal() { }/*一个构造函数*/
Animal.prototype.species = "Animal";/*给这个函数的原型对象加上species 属性,值为Animal*/
function Cat(name, color) {/*一个构造函数*/
this.name = name;
this.color = color;
}
var F = function () { };//一个函数直接量,将一个匿名函数的地址赋值给了F
F.prototype = Animal.prototype;//将Animal的原型对象的地址赋值给对这个函数直接量的原型对象
Cat.prototype = new F();//Cat构造函数用原型继承的方式继承F的实例
Cat.prototype.constructor = Cat;//改变构造函数名称
var cat1 = new Cat('cat1', 'yellow');//实例化Cat
alert(cat1.species);//Animal
</script>

代码二:
<script>
function Animal() { }//同上
Animal.prototype.species = "Animal";//同上
function Cat(name, color) {//同上
this.name = name;
this.color = color;
}
 function F() { };//上面是一个函数直接量,这次是个构造函数
F.prototype = Animal.prototype;//同上
Cat.prototype = F.prototype;//上面是原型继承,这次是直接讲2个函数的原型对象变成了同一个
Cat.prototype.constructor = Cat;//改变构造函数名
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);//Animal
</script>


2个代码执行结果是一样 但是有很多不同举例如下
1:F的作用域,仅仅从这段代码看 作用域是相同的 但是 当F定义在另外的对象或者函数内部时function F(){}它的作用域是顶级作用域而非那个上级对象或者函数
而var F=function(){},这样定义的作用域为上级对象或者函数
2:继承,Cat.prototype = new F();这是原型继承方式,当Cat.prototype原型对象被扩展或者修改之后不影响F的原型对象,而Cat.prototype = F.prototype;则会有影响
3:代码2中Cat.prototype.constructor = Cat; 那么你在代码2后面new F()这时F的constructor 属性=Cat