Constructor

parkjh9370·2021년 12월 23일
0

Constructor

  • object를 여러개 복사해 쓸수 있게 만들어준 생성기

Instance

  • constructor 에서 새로 생성되는 object
	// Constructor : makeStudent
	// Instance : this
	// (constructor 생성 시 일반 함수와는 다르게 맨 앞을 대문자로 만들어준다.)
	function MakeStudent(name, age) {
            this.name = name;
            this.age = age;
            this.sayHi = () => {
                console.log('안녕하세요 ' + this.name+ ' 입니다')
            }
        }

	let student1 = new MakeStudent('Park', 20);
        console.log(student1)
        // makeStudent {name: 'Park', age: 20, sayHi: ƒ}

        student1.sayHi();
        // 안녕하세요 Park 입니다
        
        let student2 = new MakeStudent();
        console.log(student2)
        // makeStudent {name: undefined, age: undefined, sayHi: ƒ}

사용 예시

  • 상품마다 부가세() 라는 내부 함수를 실행하면 콘솔창에 상품가격 * 10% 만큼의 부가세금액이 출력하고 싶다면?
	function Product(상품명, 가격){
            this.name = 상품명;
            this.price = 가격;
            this.부가세 = () =>{
                console.log(this.price * 0.1)
            }
        }

        let product = new Product('shirts', 50000);
       
        product.부가세()
        // 5000

0개의 댓글