객체는 상태를 나타내는 프로퍼티와 동작을 나타내는 메서드를 하나의 논리적인 단위로 묶은 복합 자료구조이다.
const circle = {
radius : 5,
getTest() {
return 2 * circle.radius
}
}
console.log(circle.getTest())
개발자의 의도와 상관없이 발생한 암묵적 전역은 오류를 발생시키는 원인이 될 가능성이 크므로, var,let,const 키워드를 사용하여 변수를 선언한 다음 사용해야 한다.
function Circle(r) {
???.r = r //이시점에는 생성자 함수 자신이 생성할 인스턴스를 가리키는 식별자를 알수 없다.
}
Circle.prototype.getTest = function () {
//알수 없다.
return 2 * ???.r
}
자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this 를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다.
함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달되고, this도 지역 변수처럼 사용할 수 있다. 단, this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
바인딩
strict mode가 적용된 일반함수
this = undefinedvar value. =1
const obj = {
value :100,
foo() {
const that = this //
setTimeout(function () {
console.log(that.value) //100
}
...

function Person (name) {
this.name = name,
getName(function () {
return this.name
})
}
const me = new Person('Lee')
//getName 메서드 내부의 this 는 me 를 가리킨다.

const test = {
r:5,
getTest(){
return this.r
}
}
this === test
function getThis () {
return this
}
const arg = {a:1}
console.log(getThis()) //window
console.log(getThis.apply(arg))//{a:1}
console.log(getThis.call(arg))//{a:1}
this 를 갖게 된다.returnThis 가 선언되기 직전에 유효한 this 는 window 객체 이다.const returnThis = () => this;
const obj = {
name:'obj',
returnThis: returnThis,
returnThis2: () => this
};
console.log(obj.returnThis() === window); // true
this 는 이벤트를 보낸 요소로 설정 된다.function checkThis(event) {
console.log(this === event.currentTarget); // true
}
const element = document.getElementById('something')
element.addEventListener('click', checkThis, false)
| 함수 호출 방식 | this 바인딩 |
|---|---|
| 일반 함수 호출 | 전역 객체 |
| 메서드 호출 | 메서드를 호출한 객체 |
| 생성자 함수 호출 | 생성자 함수가 생성할 인스턴스 |
| Function.prototype.apply/call/bind 메서드에 의한 간접 호출 | Function.prototype.apply/call/bind 메서드에 첫번째 인수로 전달한 객체 |