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

js中可以这样定义对象,我凌乱了,搞不懂。
就是将cat.prototype.showName放在函数体内。

function cat(color,name)
{
animal.apply(this,arguments);
this.color=color;
this.name=name;
cat.prototype.showName=function(){
console.log("the name is"+this.name);
}
}

我以前碰到的写法都是
function cat(color,name)
{
animal.apply(this,arguments);
this.color=color;
this.name=name;
}
cat.prototype.showName=function(){
console.log("the name is"+this.name);
}
可是今天碰到第一种写法竟然没有报错,不知道为什么,如果第一个写法没有什么问题,那么js中经典的动态原型写法不就是多此一举吗?
动态原型写法是:

<html>
<body>
<script type="text/javascript">
function Car(sColor,iDoors,iMpg) {
  this.color = sColor;
  this.doors = iDoors;
  this.mpg = iMpg;
  this.drivers = new Array("Mike","John");
  
  if (typeof Car._initialized == "undefined") {
    Car.prototype.showColor = function() {
      alert(this.color);
    };
Car.prototype.showDoors = function() {
      alert(this.doors);
    };
    Car._initialized = true;
  }
}
var oCar1 = new Car("red",4,23);
var oCar2 = new Car("blue",3,25);
oCar1.drivers.push("Bill");
document.write(oCar1.drivers);
document.write("<br />")
document.write(oCar2.showDoors());
</script>
</body>
</html>

当初就是为了将prototype内的东西写进函数体内,设计了动态原型写法。这不是和第一种写法一样了吗?第一种写法为什么没有出现错误呢?
js function prototype html

------解决方案--------------------
prototype效果多少些,不用重复创建,this.这样需要动态创建对象属性
------解决方案--------------------
第一种每次调用构造函数,不都等于重新写了遍原型的showName方法么。