<aside> 💡 코어 자바스크립트 3장 - this
</aside>
함수내에서 this 가 사용될때, 함수의 this 로 동작하는 경우와 메소드의 this 로 동작하는 경우가 있다. 둘의 구분은 해당 함수의 호출방식에 따라 결정된다.
function func() {
console.log(this);
}
func() // 함수
// this === global 객체
var obj = {
f: func
}
obj.f() // 메소드
// this === obj
xxx.func()
처럼 앞에.
이 있으면, 메소드로 동작한다.func()
처럼 호출되는 경우, this 는 글로벌 객체다. (설계상의 오류라고 인정했다고..)
객체 내의 메소드 안에서 호출되는 함수의 경우에도, 같은 rule 이 적용된다.
function func() {
console.log(this);
}
var obj =
f: function () {
console.log(this);
func();
}
}
obj.f()
// this === obj
// this === global 객체
arrow function 은 this 바인딩이 되지않는다.
const func = () => console.log(this);
const obj = {
f: () => {
console.log(this);
func();
}
}
obj.f()
// this === global 객체
// this === global 객체
const obj2 = {
f: function () {
console.log(this);
const innerFunc = () => console.log(this);
}
}
obj2.f()
// this === obj2
// this === obj2
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/애로우_펑션 arrow function 의 더 많은 것들..
전연변수를 선언하면, 자바스크립트 엔진은 이를 전역객체의 프로퍼티로 할당한다.
var a = 1;
console.log(a); // 1
console.log(window.a); // 1
console.log(this.a); // 1
new 명령어로 함수를 호출하면, 함수가 생성자로서 동작한다. 생성자 함수 내부의 this는 객체 인스턴스 자신을 가리킨다.
var Cat = function(name) {
this.name = name;
}
var cat1 = new Cat('cat1');
var cat2 = new Cat('cat2');
// cat1 = { name: 'cat1' }
// cat2 = { name: 'cat2' }