JavaScript定义类和对象

  1. //方法一
  2. functionCar(sColor,iDoors,iMpg){
  3. this.color=sColor;
  4. this.doors=iDoors;
  5. this.mpg=iMpg;
  6. this.drivers=newArray(“Mike”,“Sue”);
  7. }
  8. Car.prototype.showColor=function(){
  9. alert(this.color);
  10. };
  11. varoCar1=newCar(“red”,4,23);
  12. varoCar2=newCar(“blue”,3,25);
  13. oCar1.drivers.push(“Matt”);
  14. alert(oCar1.drivers);//outputs“Mike,Sue,Matt”
  15. alert(oCar2.drivers);//outputs“Mike,Sue”
  16. //方法二
  17. functionCar(sColor,iDoors,iMpg){
  18. this.color=sColor;
  19. this.doors=iDoors;
  20. this.mpg=iMpg;
  21. this.drivers=newArray(“Mike”,“Sue”);
  22. if(typeofCar._initialized==“undefined”){
  23. Car.prototype.showColor=function(){
  24. alert(this.color);
  25. };
  26. Car._initialized=true;
  27. }
  28. }

使用了prototype后,可以用instanceof 来判断这个对象是否属于一个类的实例。比如:oCar1 instanceof Car

你可能感兴趣的:(JavaScript,prototype)