- 객체일때 (일반함수 사용)
- 객체일때 (화살표함수 사용)
- 생성자 함수 일때 (일반함수 사용)
- 생성자 함수 일때 (화살표함수 사용)
var a = 10;
var obj = {
a: 20,
b() {
console.log(this); // this === obj. 20 출력
function c() {
console.log(this); // this === window. 10 출력
}
c();
},
};
obj.b();
- 결과
{a: 20, b: ƒ} Window {0: global, window: Window, self: Window, document: document, name: "", location: Location, …}직접 관련된 첫번째 this는 해당 객체를 출력하고
내부에서 생성된 새로운 함수는 함수 자체로 this가 window 객체로 바뀌게된다.
var a = 10;
var obj = {
a: 20,
b() {
console.log(this); // this === obj. 20 출력
const c = () => {
console.log(this); // this === window. 10 출력
};
c();
},
};
obj.b();
- 결과
{a: 20, b: ƒ} {a: 20, b: ƒ}화살표함수는 this를 가지고 있지 않기 때문에 화살표 함수 내에서 this가 사용되었다면 그 this가 무엇인지를 찾으러 올라가면서 가장 가까운 obj를 찾고 즉, 같은 결과이다.
function RockBand(members) {
this.members = members;
this.perform = function () {
console.log(this);
function c() {
console.log(this);
}
c();
setTimeout(function () {
console.log(this);
function p() {
console.log(this);
}
p();
}, 1000);
};
}
let theOralCigrettes = new RockBand([
{
name: "takuya",
perform: function () {
console.log("Sing a e u i a e u i");
},
},
]);
theOralCigrettes.perform();
RockBand {members: Array(1), perform: ƒ}
Window {0: global, window: Window, self: Window, document: document, name: "", location: Location, …}
Window {0: global, window: Window, self: Window, document: document, name: "", location: Location, …}
Window {0: global, window: Window, self: Window, document: document, name: "", location: Location, …}
처음 콘솔로 this와 함수로 바로 연결된 콘솔은
RockBand를 가리키고 그 내부에서 새롭게 만든 함수는 window객체를 가리키고 마찬가지로 setTimeout 매개변수로 만든 함수와 그 내부의 새롭게 만든 함수도 window객체를 가르킨다.
function RockBand(members) {
this.members = members;
this.perform = function () {
console.log(this);
function c() {
console.log(this);
}
c();
setTimeout(() => {
console.log(this);
const p = () => {
console.log(this);
};
p();
}, 1000);
};
}
let theOralCigrettes = new RockBand([
{
name: "takuya",
perform: function () {
console.log("Sing a e u i a e u i");
},
},
]);
theOralCigrettes.perform();
- 결과
RockBand {members: Array(1), perform: ƒ} Window {0: Window, window: Window, self: Window, document: document, name: "", location: Location, …} RockBand {members: Array(1), perform: ƒ} RockBand {members: Array(1), perform: ƒ}setTimeout의 매개변수인 함수를 화살표함수로 바꾸어 해당 내부의
console.log(this)는 가장 가까운 this 객체인 RockBand를 찾고
마찬가지로 해당 내부의 새롭게 선언한 p함수도 화살표함수이므로 내부의 this는 가장 가까운 this 객체인 RockBand를 찾아 결과는 이와같다.