ES2015 모듈에서는 strict 모드 자동 적용됨
function a() {
//'use strict'; //만약 strict 모드를 사용을 위해 주석을 풀면, this는 undefined가 됨
console.log(this);
}
//a()
console.log(globalThis)
//브라우저 js 의 전역은 window, 최근에 업데이트되어서 window가 globalThis 로 바뀜
// node 의 전역은 global, node도 global이 globalThis로 바뀜
this는 어디서 호출하느냐에 따라 달라짐
obj 안에서 this는 obj
하지만 sayN에 obj.sayName을 대입하고
sayN을 호출하면 this가 바뀜
this 는 함수가 호출 될 때 결정됨. 함수를 전역 스코프에서 호출하면 global이 this가 되고
객체에서 호출하면 this는 호출한 객체가 될 것임
const obj = {
name:'zerocho',
sayName() {
console.log(this.name);
}
}
obj.sayName() //zerocho
const sayN = obj.sayName;
sayN() //undefined
또한 obj의 sayName이 화살표 함수면 this는 달라짐
화살표 함수로 선언하면 부모의 this를 물려받음
const obj = {
name:'zerocho',
sayName:()=> {
console.log(this.name);
}
}
obj.sayName() //undefined
function Human (name) {
this.name = name;
}
const xxx = new Human('zerocho')
console.log(xxx.name) //zerocho
console.log(new Human('zerocho').name) //위와 같음 zerocho
아래의 스코프 체인은
inner -> sayName -> anonymous
첫번째 this는 obj3.sayName()에 의해 실행되므로 this는 obj3
두번째 this는 inner 함수가 그 자체로 호출되므로 this는 global임
const obj3 = {
name:'zerocho',
sayName(){
console.log(this.name);// zerocho
function inner() {
console.log(this.name)//undefined
}
inner();
}
}
obj3.sayName()
화살표 함수로 하면 this는 함수가 속한 스코프의 this로 정의됨
const obj3 = {
name:'zerocho',
sayName(){
console.log(this.name);// zerocho
const inner=()=> {
console.log(this.name)//zerocho
}
inner();
}
}
obj3.sayName()
this는 호출하는 방법에 따라 결정됨!
'Node.JS' 카테고리의 다른 글
[Node.js 교과서] 2-10. 파일 시스템 (0) | 2023.12.27 |
---|---|
[Node.js 교과서] 2-x. 예외 처리하기 (0) | 2023.12.26 |
[Node.js 교과서] 2-7. OS, Path (0) | 2023.12.19 |
[Node.js 교과서] 2-6. process (0) | 2023.12.19 |
[Node.js 교과서] 2-5. global, console, 타이머 (Node js의 내장객체) (1) | 2023.12.19 |