This...
자바스크립트에서의 this 는 일반 OOP 에서의 this 와 차이가 있다. 이는 자바스크립트에서 전역객체를 제공하기 때문에 this 가 지칭하는 객체를 혼동하는 경우가 생긴다.
this 가 어떤 객체를 지칭하는지를 정확하게 이해하려면 함수가 일반 함수인지 객체 함수인지를 구분할수 있어야 한다.
- 일반함수호출
- 객체함수호출
일반함수호출
자바스크립트는 특정 객체에 속하지 않은 변수나 함수는 전역 객체인 window 소속이 된다. 결국 일반 함수라는 것은 window의 함수를 의미한다.
function a(){
this.name="kkang"
console.log("a()..."+name)//kkang
console.log("a()..."+this.name)//kkang
}
a()
console.log(name)//kkang
console.log(this.name)//kkang
위에 정의한 a() 는 일반 함수이다. 이 함수내에서 this.name 으로 선언한 this 는 window 객체가 된다. 결국 전역에 변수를 선언한 것이 되어 버린다.
l 엄격모드에서의 일반함수
엄격 모드로 실행하게 되면 this 가 undefined 된다.
//일반함수의 엄격모드에서 this
function b(){
'use strict'
this.name1="kkang"//error
console.log("b()..."+name1)
console.log("b()..."+this.name1)
}
b()
console.log(name1)
console.log(this.name1)
함수내에 ‘use strict’ 를 추가한 것 밖에 없다. 그런데 실행시 에러가 난다.
l 함수 중복
//일반함수.. inner 함수..
function c(){
console.log(this == window)//true
this.name2="kkang"
function c1(){
console.log(this == window)//true
console.log("c1()..."+this.name)//kkang
}
c1()
console.log("c()..."+this.name)//kkang
}
c()
console.log(this.name)//kkang
inner 함수내에서 this 도 window 이다.
자바스크립트에서 클래스를 선언할 때 prototype 을 지정하지 않으면 객체 맴버가 아니라 static member 가 된다. 그럼으로 이 경우에도 this 는 window 객체가 된다.
객체함수
//Prototype...
function d(){
console.log(this == window)//false
this.name3="kkang"
d.prototype.d1 = function(){
console.log(this == window)//false
console.log("d1()..."+this.name3)//kkang
}
function d2(){
console.log(this == window)//true
console.log("d2()..."+this.name3)//undefined
}
d2()
console.log("d()..."+this.name3)//kkang
}
var obj3 = new d()
obj3.d1()
console.log(this.name3)//undefined
위의 d() 함수는 클래스 선언이 된다. d 라는 클래스내에 d1 함수와 d2 함수를 추가했지만 d1 은 prototype 을 이용하여 d 클래스 멤버로 선언했고 d2는 prototype 을 지정하지 않았다.
이렇게 되면 d2 는 window 소속이 되며 d1 은 d 소속이 된다.
결국 각 함수내에서 this 가 지칭하는 객체가 다르게 된다.
json 스타일로 객체를 만드는 경우도 마찮가지다
//객체함수.. json...
var e = {
name4: "kkang",
e1: function() {
console.log(this === window); // => false
function e2() {
console.log(this === window); // => true
console.log("e2()..."+this.name4)//undefined
}
e2()
console.log("e1()..."+this.name4)//kkang
}
};
e.e1()
console.log(this.name4)//undefined
è정리해 보자면 일반 함수는 this 는 window… 객체 함수의 this 는 해당 객체..