괴발개발/Javascript+JQuery

JS_객체

moonday 2021. 6. 18. 00:42

더보기

    var 객체명 = {

      변수명 : 값,

      변수명 : 값,

      메서드명 : function(){

        구현;

      }

    }

  var student = {
    name : '내이름은푸우',
    grade : 1,
    class : 1,
    num : 1,
    print : function(){
      document.write(`${this.grade}학년 ${this.class}반 ${this.num}번 ${this.name}<br>`);
    }
  }
  
   //확인하기위해 메소드 호출
  student.print();

  //자바랑 다르게 새로운 속성을 추가 가능
  student.age=17;

  //메소드를 수정 가능
  student.print=function(){
    document.write(`${this.grade}학년 ${this.class}반 ${this.num}번 ${this.name} 나이: ${this.age} <br>`)
  }

  //확인하기위해 메소드 호출
  student.print();
  
  //속성을 삭제 가능
  delete student.age;
  student.print();

  //메소드를 추가할 수 있음
  student.upGrade = function(){
    this.grade= this.grade+1;
  }

  //추가한 메소드를 실행
  student.upGrade();

  //확인하기위해서 메소드 호출
  student.print();

더보기

- 객체 생성자 함수: 해당 함수를 이용하여 여러 객체를 생성할 수 있다.

    function 클래스명(매개변수){

      this.속성 = 매개변수;

      this.속성 = 매개변수;

      this.메소드 = function(){

        구현;

      }

    }

    

    

    var 객체명 = new 클래스명(매개변수);

function Student(grade, classNum, num, name, age){
      this.grade = grade;
      this.classNum = classNum;
      this.num = num;
      this.name = name;
      this.age=age;
      this.print = function(){
        document.write(`${this.grade}학년 ${this.classNum}반 ${this.num}번 ${this.name} 나이: ${this.age} <br>`)
      }
    }

    var std1 = new Student(1,1,1,'설리반',17);
    var std2 = new Student(1,1,2,'마이크',17);
    std1.print();
    std2.print();


    console.log(std1.name);
    console.log(std1['name']);
    
    
    /* for in문 - 자바의 향상된 for문과 같은 기능*/
    for(var index in std1){
    console.log(index + " : " + std1[index]);
    }

'괴발개발 > Javascript+JQuery' 카테고리의 다른 글

JS_날짜(Date, Date형식 수정)  (0) 2021.06.21
JS_반복문(for in, for of, forEach)  (0) 2021.06.21
JS_클래스  (0) 2021.06.18
JS_배열  (0) 2021.06.18
JS_재귀함수  (0) 2021.06.18