본문 바로가기
JavaScript(JS)

JS02

by EUN-JI 2023. 11. 2.
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>JS Object</title>

        <script>
            //js에서 객체의 2가지 종류
            //1. 내장객체 : document, window, navigation..등 ..Date(), Array()등 (내일수업)
            //2. 개발자가 정의하는 객체

            //개발자가 만드는 객체의 방법은 2가지[지금은 class문법이 추가되어 총3개임.. 나중수업]
           
            //1) 리터럴 객체[객체를 생성하면서 멤버를 설계하는 방식]
            var person= {
                //멤버변수 - property
                name: "sam",
                age: 20,


                //멤버함수 - method
                show: function(){
                    //document.write("show function .. <br>");  

                     //일반적으로 멤버함수의 역할을 멤버변수를 제어하는 기능을 작성함.
                   //멤버변수의 값을 출력해주는 기능으로 코딩
                    //document.write(name+" , "+age+"<br>");  //에러 :name, age변수가 멤버변수인지모름
                    //js는 객체안에서 멤버에 this키워드 붙여야함.
                    document.write("person show : "+this.name+" , "+this.age+"<br>");
                }
            };

            //객체의 멤버변수 사용
            document.write("이름 : "+ person.name+" , ");
            document.write("나이 : "+ person.age+" <br>");
           

            //객체의 멤버함수 사용
            person.show();

            //리터럴 객체의 문제점.. 같은 긱능을 가진 또 다른 객체가 필요할때.
            //모든 멤버에 대한 설계를 다시 해야함.
            var person2={
                name:"robin",
                age: 25,
                show:function(){
                    document.write("person2 show : "+ this.name+" , "+this.age+"<br>");
                },

                //멤버함수도 파라미터를 가질 수 있음.
                add:function(a,b){
                    var c= a+b;
                    document.write("add fuction :  "+ c+" <br>");
                }
            }

            person2.show();
            person2.add(5,3);

            person2.show(100);  //파라미터 없는 함수에 값을 주면 그값을 무시함... 에러는 아님.
           // person.add(5,3); //person 객체에 없는 메소드를 호출하면 ..  에러 !!!!즉, 이 줄 다음 동작 안함.

           //js는 워낙 유연한 언어여서.. 객체를 생성한 후에도 언제든 멤버를 추가할 수 있음.
           //멤버변수 추가
           person.address= "seoul";  //property추가
           document.write(person.name+" , " + person.age+ " , " + person.address + "<br>");

           //멤버함수 추가
           person.out= function(){
            document.write("out function : " + this.name + " , " + this.age + " , " + this.address+ "<br>");

           }

           //새로 추가한 out메소드를 호출하여 실행해보기
           person.out();

           //혹시 추가하지 않은 멤버변수를 출력하려고 시도하면?   ,,변수는 에러아님 .. undefined
           document.write("전화번호 : " + person.tel+ "<br>");

           document.write("<hr>");

            //2) 생성자 함수 [Java의 class와 비슷한 역할임. new 키워드로 객체 생성 방식.]

            function Student(){
                //멤버변수
                this.name= "hong";
                this.age= 23;
                this.major= "web";


                //멤버함수
                this.show=function(){
                    document.write("Student show : " + this.name + " , " + this.age+ " , " + this.major+ "<br>");
                }
            }

            //위 생성자 함수를 만들었다고 객체가 된 것이 아님.. 단지 설계만 한것임
            //사용하려면.. 객체로 생성해야함. .. .객체 생성 키워드 new
            var stu= new Student();
            stu.show();

            //또 다른 학생객체가 필요하면?

            var stu2= new Student();
            stu2.show();
            //new로 생성했더니.. 편하긴 한데 .. 같은 값을 가지고 있음.. 멤버 값으 변경
            var stu3= new Student();
            stu3.name="park";
            stu3.age=25;
            stu3.major="android";
            stu3.show();

            //근데 .. 이렇게 객체 생성후에 멤버값을 일일이 대입하니.. 좀 짜증.. 코드도 길어지고..
            //객체를 생서하면서 값을 전달.. 하고 싶음. 자바에서는 이를 생성자함수 [constructor]라고 불렀음
            //js는 class대신에 이미 생성자 함수로 설계하고 있으니 .. 함수의 파라미터만 전달받으면 됨
            function Stu(name,age,major){

                //멤버변수에 전달받은 파라미터 값들 초기화..
                this.name= name;
                this.age= age;
                this.major= major;

                this.show= function(){
                document.write("Stu show : " + this.name + " , " + this.age+ " , " + this.major+ "<br>");
                }

                //메소드의 파라미터와 리턴연습..
                //getter , setter method 만들기
                this.getName= function(){
                    return this.name;
                }

                this.setName= function(name){
                    this.name= name;
                }

                //원래는 age, mejor도 getter, setter 를 만들어야함.. 시간상 생략

            }

            var s=new Stu("kim",22,"java");//객체를 생성하면서 값 전달
            s.show();

            //혹시 생성자에 값을 안주면?  ..에러아님. ..undefined
            var s2=new Stu();
            s2.show();


            //getter사용해 보기
            var name = s.getName();
            document.write("이름 : " + name + " <br>");

            //setter 사용해 보기
            s.setName("LEE");
            s.show();

            ///////////////////////////////////////p 337자동차 예제실습

           
        </script>
    </head>

    <body>
       
    </body>
</html>

'JavaScript(JS)' 카테고리의 다른 글

JS05  (1) 2023.11.03
JS04  (0) 2023.11.02
JS03  (0) 2023.11.02
JS01  (1) 2023.10.31
JS//01  (0) 2023.08.30