this

wonyoung·2024년 4월 2일

Javascript

목록 보기
31/36

브라우저 js //window
node // global
-> globalThis로 통합됨

strict모드
-> this 는 undefined
ES2015모듈에서는 strict 자동적용

const obj = {
	name: "wonyoung",
    sayName(){
    	console.log(this.name);
    }
}
obj.sayName()
//wonyoung

const sayN = obj.sayName;
sayN()
//undefined

this는 함수가 호출될 때 정해짐

sayName: function(){
	console.log(this.name)
}

위와 아래는 같음
`새로나온문법`
sayName(){
	console.log(this.name)
}
const obj = {
	name: 'wonyoung',
    sayName(){
    	console.log(this.name);
        function inner(){
        	console.log(this.name);
        }
        inner()
    }
}
obj.sayName();
// wonyoung
// undefined
const obj = {
	name: 'wonyoung',
    sayName(){
    	console.log(this.name);
        const inner = () => {
        	console.log(this.name);
        }
        inner()
      // 화살표함수가 아닌 function inner() {}일경우에 밑의 method bind call apply 사용하여 호출하면 this는 obj
      // inner.call(obj)
      // inner.apply(obj)
      // inner.bind(obj)()
    }
}
obj.sayName();
// wonyoung
// wonyoung -> 부모의 this 물려받음

this 키워드는 주로 객체 지향 프로그래밍 언어에서 사용되며, 현재 객체를 참조합니다. 자바스크립트에서 new 키워드를 사용해 새 인스턴스를 생성하면, this는 새로 생성된 객체 인스턴스를 가리킵니다. 이를 통해 클래스나 생성자 함수 내부에서 현재 인스턴스의 프로퍼티나 메소드에 접근할 수 있습니다.
예를 들어, 자바스크립트에서 간단한 클래스를 정의하고 new를 사용해 인스턴스를 생성하는 경우를 살펴보겠습니다:

class Person {
  constructor(name, age) {
    this.name = name; // 여기서 this는 새로 생성된 Person 인스턴스를 가리킵니다.
    this.age = age;
  }
  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    // 여기서 this.name과 this.age는 현재 인스턴스의 name과 age 프로퍼티를 참조합니다.
  }
}
const person1 = new Person('John', 30); // 새 Person 인스턴스 생성
person1.greet(); // "Hello, my name is John and I am 30 years old." 출력

위 예시에서 new Person('John', 30)를 호출하면 Person 클래스의 constructor 함수가 실행됩니다. constructor 함수 내부에서 this는 새로 생성된 Person 객체 인스턴스를 가리키며, this.name과 this.age에 값을 할당합니다. 그 후, 생성된 인스턴스 person1에 대해 greet 메소드를 호출하면, 해당 메소드 내부에서도 this는 person1을 가리키게 됩니다.
this가 가리키는 대상은 함수 호출 방식에 따라 달라질 수 있지만, new 키워드를 사용해 인스턴스를 생성하는 경우에는 항상 새로 생성된 객체 인스턴스를 가리키게 됩니다.

addEventListener 예시


const header = {
  addEventListener: function(eventName, callback){
  	callback.call(this) //this가 header
    // 또는 callback.call(header)
  }
}

header.addEventListener('click',function(){
	console.log(this) //header
})
const header = document.querySeletor('.main_header');

header.addEventListener('click',() => {
	console.log(this) //window
})
function a(){}

a.apply(window) == a.bind(window)() == a.call(window)

function add(a,b){return a+b}

add.apply(null, [3, 5]) // 8
add.call(null, 3, 5) // 8

this는 ★★★★★ window ★★★★★

호출시 this가 정해짐(호출하는 방식에 따라)

  • 객체의 메서드로 호출하는 경우
  • 화살표함수는 부모의 this를 물려받음(부모함수가 어떻게 호출되는지 봐야함)
  • new
  • bind call apply
profile
😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀

0개의 댓글