// 단순 함수 호출
// 1. 일반 함수 범위에서 호출
function outside() {
console.log(this); // this는 window
// 2. 함수 안에 함수가 선언된 내부 함수 호출
function inside() {
console.log(this); // this는 window
}
inside();
}
outside();
// 객체의 메소드(Method)
// 1. 객체 또는 클래스 안에서 메소드를 실행한다면 this는 Object 자기 자신
var man = {
name: 'john',
hello: function() {
// 2. 객체이므로 this는 man을 가리킴
console.log('hello ' + this.name);
}
}
man.hello(); // 3. hello john
// 3. 일반 함수 welcome을 선언
function welcome() {
// 4. 여기서 this는 전역 객체 Window이므로, 만약 실행시키면 undefined가 뜸
console.log('welcome ' + this.name);
}
// 5. man 객체의 welcome 속성에 일반 함수 welcome을 추가
man.welcome = welcome;
// 6. welcome이 man 객체에서 호출되었으므로 welcome john이 출력됨
man.welcome();
// 7. man 객체의 thanks 속성에 함수를 선언
man.thanks = function () {
// 8. man.thanks()를 호출하면 thanks john이 출력
console.log('thanks ' + this.name);
}
// 8. 이 함수를 객체 외부에서 참조
var thankYou = man.thanks;
// 9. 객체 외부이므로 this가 Window 객체가 되어서 thanks (undefined)가 출력
thankYou();
// 10. 그럼 또 다른 객체에서 이 함수를 호출하면 어떻게 될까?
women = {
name: 'barbie',
thanks: man.thanks // 11. man.thanks 함수를 women.thanks에 참조
}
// 12. this가 포함된 함수가 호출된 객체가 women이므로 thanks barbie가 출력
women.thanks();
// 메소드 내에 함수 선언
var man = {
name: 'john',
// 1. 이것은 객체의 메소드
hello: function() {
// 2. 객체의 메소드 안에서 함수를 선언하는 것이니까 내부 함수
function getName() {
// 3. 여기서 this가 무엇을 가리키고 있을까?
return this.name;
}
console.log('hello ' + getName()); // 4. 내부 함수를 출력시키고
}
}
man.hello(); // 메소드를 실행시키면 undefined가 뜬다! this는 Window였던 것
// call(), apply(), bind()
// 1. 이것은 객체의 메소드
var man = {
name: 'john',
// 2. 객체의 메소드 안에서 함수를 선언하는 것이니까 내부 함수
hello: function() {
function getName() {
// 3. 여기서 this가 무엇을 가리키고 있을까?
return this.name;
}
// 4. 이번에는 call()을 통해 현재 문맥에서의 this(man 객체)를 바인딩해주었다
console.log('hello ' + getName.call(this));
}
}
// 이번에는 메소드를 실행시키면 john가 뜬다!
// this가 man 객체로 바인딩 된 것을 확인할 수 있다
man.hello();
// 콜백 함수
// 1. 콜백함수
var object = {
callback: function() {
setTimeout(function() {
console.log(this); // 2. this는 window
}, 1000);
}
}
// 생성자
// 1. 클래스 역할을 할 함수 선언
function Man () {
this.name = 'John';
}
// 2. 생성자로 객체 선언
var john = new Man();
// 3. this가 Man 객체를 가리키고 있어 이름이 정상적으로 출력된다
john.name; // => 'John'
// class 이용
// 1. Class Man 선언
class Man {
constructor(name) {
this.name = name;
}
hello() {
console.log('hello ' + this.name)
}
}
// 2. 생성자 실행
var john = new Man('John');
john.hello(); // 3. hello John 출력
// 화살표 함수(Arrow function)
// 1. 화살표 함수
var obj = {
a: this, // 2. 일반적인 경우 this는 window,
b: function() {
console.log(this) // 3. 메소드의 경우 this는 객체
},
c: () => {
console.log(this)
// 4. 화살표 함수의 경우 정적 컨텍스트를 가짐, 함수를 호출하는 것과 this는 연관이 없음
// 5. 따라서 화살표 함수가 정의된 obj 객체의 this를 바인딩하므로 this는 window
}
}
obj.b() // 6. obj
obj.c() // 7. window
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter