就是将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内的东西写进函数体内,设计了动态原型写法。这不是和第一种写法一样了吗?第一种写法为什么没有出现错误呢?jsfunctionprototypehtml