본문 바로가기

개발하자/자바스크립트

객체를 생성하는 방식 두가지

1  function Car(c,s){
  this.color=c;
  this.speed=s;
 }
 var car=new Car("red",100);
 document.write(car.color);
 document.write(car["speed"]);


2 var car={  color:"blue",
   speed:100,
   getBrand:function(){return"현대";}
 };
 document.write(car.color);
 document.write(car["speed"]); 
 document.write(car.getBrand);

 

[ex]
<html>
 <body>
 <script>
 //here

 var dog1=new Dog("똘망이","씨추",10);
 document.write(dog1.name);
 document.write(dog1.getBreed());
 document.write(dog1.getAge());

 var dog2=new Dog("뚱돌이","페키니즈",5);
 document.write(dog2.name);
 document.write(dog2.getBreed());
 document.write(dog2.getAge());
 </script>
 </body>
</html>
[an]
<html>
 <body>
 <script>
 function Dog(a,b,c){
  this.name=a;
  this.getBreed=function(){ return b; }
  this.getAge=function(){ return c; }
 }

 var dog1=new Dog("똘망이","씨추",10);
 document.write(dog1["name"]);
 document.write(dog1["getBreed"]());
 document.write(dog1.getAge());

 var dog2=new Dog("뚱돌이","페키니즈",5);
 document.write(dog2.name);
 document.write(dog2.getBreed());
 document.write(dog2.getAge());
 </script>
 </body>
</html>