🗃️javascript/이론정리

js의 this 반복정리

하얀성 2024. 1. 5. 07:06

 this의 의미는 사용되는 컨텍스트에 따라 달라집니다. JavaScript에서 this의 동작 방식을 이해하는 것은 종종 혼란스러울 수 있습니다.

 

  1. 글로벌 컨텍스트에서의 this: JavaScript의 글로벌 실행 컨텍스트에서 this는 글로벌 객체를 가리킵니다. 브라우저에서는 window 객체가 됩니다.
  2. 함수 내에서의 this: 일반 함수에서 this의 값은 함수 호출 방식에 따라 달라집니다. 기본적으로, 일반 함수에서 this는 글로벌 객체를 가리키지만, 엄격 모드('use strict')에서는 undefined가 됩니다. 또한, 객체의 메소드로서 함수가 호출될 때 this는 해당 메소드를 호출한 객체에 바인딩됩니다.
  3. 화살표 함수에서의 this: 화살표 함수는 자신만의 this 바인딩을 가지지 않습니다. 대신, 화살표 함수는 자신을 포함하고 있는 외부 함수의 this 값을 상속받습니다.
  4. 클래스 컴포넌트에서의 this: React 클래스 컴포넌트에서 this는 컴포넌트 인스턴스를 참조합니다. 이를 통해 인스턴스의 프로퍼티(예: this.state, this.props)와 메소드(예: this.handleClick)에 접근할 수 있습니다.

 


헷갈린 this 내용

export default class App extends Component {
 

getStyle = () => {
  return {
    padding: "10px",
    borderBottom: "1px #ccc dotted",
    TextDecoration: 'none'
  }
}

todoData = [
  {
    id:"1",
    title:"공부하기",
    completed: true
  },
  {
    id:"2",
    title:"청소하기",
    completed: false
  },
];

handleClick = (id) => {
  let newTodoData = this.todoData.filter(data => data.id !== id)
  console.log('newTodoData', newTodoData)
}

  render() {
    return (
        <div className='container'>
          <div className='todoBlock'>
            <div className="title">
              <h1>할 일 목록</h1>
            </div>

          {this.todoData.map((data) => (  // 여기 this. 는 App 클래스를 말하는 것 같은데 맞니?
            <div style={this.getStyle()} key={data.id}>
            <input type="checkbox" defaultChecked={false} />
              {data.title}
            <button style={this.btnStyle} onClick={() => this.handleClick(data.id)}>x</button>
            // this.btnStyle 에서 this는 App을 말하니? 아니면 button을 말하나?
          </div>
          ))}
          </div>
        </div>
    )
  }
}

 

React의 클래스 안의 this는 객체 인스턴스를 뜻한다. 이 this는 둘다 App클래스의 인스턴스를 의미.