javascript

[javascript] 클래스 필드란

우주유령 2022. 4. 5. 21:38
728x90
반응형

java에서는 아래와 같이 사용할 수 있다.

public class Person{
	priavte String firstName = ""; // 클래스 필드에 클래스 멤버 생성
	public String getName() {
		return this.firstName;
	}
}

firstName이 생성된 곳을 클래스 필드라고 한다.

 

ES6+이후 javascript에서도 클래스 필드에 선언 할 수 있게 되었다.

 

class Person{
	firstName = "Lee"; // 클래스 필드에 인스턴스 변수 선언
}

const p = new Person(); // Person {firstname:"Lee"}

클래스필드에 변수를 선언하면 인스턴스의 변수가 된다.

 

위의 코드는 아래와 같다.

class Person{
	constructor(){
		this.firstName = "Lee";
	}
}

마찬가지로, 클래스필드에 함수를 선언하면 

프로토타입의 method가 아니라 인스턴스의 method이다.

따라서 필드에 함수를 할당하는것은 권장하지 않는다.

 

권장되지는 않지만 아래와 같이 사용할 수도 있다.

class Component {
	constructor{
		this.button.onclick = this.handleClick;
	}
//화살표 함수 내부의 this는 언제나 상위 컨텍스트의 this를 가리킨다.
	handleClick = () => {
		console.log(this);
	}
}

handleClick이 일반 함수로 선언되어있을 경우,

this는 기본적으로 바인딩되지 않는다. 이 경우 this가 undefined이다.

class Component {
	constructor{
		this.button.onclick = this.handleClick;
	}
// class에서는 this를 자동으로 바인딩하지 않는다.
	handleClick() {
    	console.log(this); //undefined
    }
}

따라서 bind를 이용해 this를 바인딩해주어야 한다.

class Component {
	constructor{
		this.button.onclick = this.handleClick.bind(this); //this binding
	}
	handleClick() {
    	console.log(this); //class Component
    }
}

 

 

화살표함수의 this는 항상 상위 컨텍스트의 this를 가리키므로 bind하는 과정이 필요하지 않다.

bind하는 과정을 피하기 위해 화살표 함수를 사용할 수 있다. 하지만 이런 방법은 실험적이고, 권장되지 않는 방법이다.

 

728x90
반응형