ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 생성자 함수
    JavaScript 2022. 9. 30. 02:09

    1. new 함수명(); 을 실행하면
    2. this = {}  : 빈 객체를 만들고 this에 할당 (실제로 이 줄은 코드에 없음)
    3. this = {} 에 할당될 프로퍼티들 // this.name = name; //  this.age = age; // this에 property 추가
    4. return this; // 마지막으로 this 를 반환 // 실제로 이 줄은 코드에 없음

    이렇게 쓰는 이유 : 일일이 객체 리터럴을 쓰는 것보다 빠르고 일관성도 있다.

     

    생성자 함수에 this ={} 가 생략되어 있으며,

    this.프로퍼티이름 이 모두 저 생략된 코드줄에 들어간다는 것을....

     

    이걸 말이야, 진작에 알려줬어야지.

    저것만 알려줬으면 이해가 바로 될텐데.


    function User(name, age){   // User 첫글자는 대문자로 // 생성자 함수는 붕어빵 틀
        this.name = name;
        this.age = age;
        this.sayName = function(){   //자기 이름을 말하는 메서드를 추가해보자
            console.log(this.name);
        }
    }
    
    let user1 = new User('Mike', 30); // 생성된 객체는 붕어빵
    let user2 = new User('Jane', 22);
    let user3 = new User('Tom', 17); 
    let user5 = new User('Han', 40);
    user5.sayName(); // 'Han' // 이걸 호출했을 때 sayName 함수의 this는 이 앞의 user5가 된다.
    
    //1. new 함수명(); 을 실행하면
    //2. this = {}  //빈 객체를 만들고 this에 할당 //실제로 이 줄은 코드에 없음
    //3. this.name = name; //  this.age = age; // this에 property 추가
    //4. return this; // 마지막으로 this 를 반환 // 실제로 이 줄은 코드에 없음
    
    //이렇게 쓰는 이유 : 일일이 객체 리터럴을 쓰는 것보다 빠르고 일관성도 있다.

     

    function Item(title, price){
        //this = {};
        this.title = title;
        this.price = price;
        this.showPrice = function(){
            console.log(`가격은 ${price}원 입니다.`);
        }
    
        //return this;
    }
    
    const item1 = new Item('인형', 3000)
    const item2 = Item('가방', 3000) // new를 지워보자 //undefined 출력 
    const item3 = new Item('지갑', 3000) 
    // new가 없으면 걍 함수를 실행하는 건데, return해주는게 없으니 undefined를 반환하고
    // 그 undefined가 item2에 들어가게 된다.
    
    console.log(item1, item2, item3);
    //Item { title: '인형', price: 3000, showPrice: [Function (anonymous)] } 
    //Item { title: '가방', price: 3000, showPrice: [Function (anonymous)] } 
    //Item { title: '지갑', price: 3000, showPrice: [Function (anonymous)] }
    
    item3.showPrice(); // 가격은 3000원 입니다.
Designed by Tistory.