생성자 함수와 this 키워드(Constructor Functions and keyword "this")

2023. 5. 9. 12:29프론트엔드/기술 면접 (JavaScript Interview Questions)

반응형

 

function User(firstName, lastName, age, gender) {
	this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
}

const user1 = new User('Jill', 'Smith', 33, 'female');
const user2 = new User('Bob', 'Smith', 24, 'male');

user1 and user2 are objects of the class User

 

user1과 user2는 User 클래스의 객체입니다.

 

You might be wondering how all these properties got assigned correctly, and that brings us back to the "this" keyword that we mentioned earlier. When we create our constructor function, we use the "this" keyword to assign the properties. When it comes to constructor functions, the "this" keyword, it does not refer to the function that it is in, but instead, "this" refers to the object that will be created by the constructor function. 

 

이러한 모든 속성이 어떻게 올바르게 할당되었는지 궁금할 수 있으며, 이는 앞에서 언급한 "this" 키워드로 다시 돌아갑니다. 생성자 함수를 만들 때 "this" 키워드를 사용하여 속성을 할당합니다. 생성자 함수의 경우 "this" 키워드는 자신이 속한 함수를 가리키는 것이 아니라 생성자 함수에 의해 생성될 객체를 가리키는 것입니다.

 

 

 

반응형