this
๊ธฐ๋ณธ์ window
์๋ฌด html ํ์ผ์์ <script> ํ๊ทธ ์ด๊ณ
console.log(this) ์ฐ์ผ๋ฉด window ๋์ด
index.html
<html>
<script>
console.log(this); //window
</script>
</html>
๋ง์ฐฌ๊ฐ์ง๋ก ํจ์์์์๋ window
function test() {
console.log(this); // window
}
Q. Window?
window๋ ๋ชจ๋ ์ ์ญ๋ณ์, ํจ์ , DOM ์ ๋ณด๊ดํ๊ณ ๊ด๋ฆฌํ๋ ์ ์ญ๊ฐ์ฒด
์ ์ฒด๋ฅผ ๊ฐ์ธ๋ object ๋ผ๊ณ ์๊ฐํ๋ฉด ํธํจ
object ๋ด์ ํจ์์์๋ ๋ถ๋ชจ object
var obj1 = {
data : 'data',
fun1 : function() {console.log(this)}
}
obj1.fun1(); //obj1์ด ์ถ๋ ฅ๋๋ค.
object ๋ด์์์ this๋ ๋ถ๋ชจ object๋ฅผ ๊ฐ๋ฅดํจ๋ค
์ฌ๊ธฐ์ obj1์ด ์ถ๋ ฅ๋จ
var obj2 = {
data : {
fun2 : function() {console.log(this)}
}
}
obj2.data.fun2(); // this๋obj2.data
์ฌ์ค 1๋ฒ๊ณผ 2๋ฒ์ ๋์ผํ ์ด์ผ๊ธฐ
<script>
function fun1() {
console.log(this);
}
window.fun1 = function() {
console.log(this)
}
//์ ์ฝ๋๋ ๋๋ค ๊ฐ์ ๋ด์ฉ์
</script>
์ฐ๋ฆฌ๊ฐ ์๋ฌด ์ ์ธ์์ด ํจ์๋ ๋ณ์ ๋ง๋ค๋ฉด ๊ทธ๊ฑด ์ ๋ถ window ๊ฐ์ฒด์ ๋ด๊ธด๋ค.
constructor ์์์ ์ฐ๋ฉด constructor๋ก ์๋ก ์์ฑ๋๋ object
function fun3() {
this.name = 'Lee';
}
์ฌ๊ธฐ์ this๋ fun3์ผ๋ก๋ถํฐ ์๋ก ์์ฑ๋ object๋ฅผ ์๋ฏธํจ
var obj3 = new fun3();
console.log(obj3.name); //'Lee'๊ฐ ์ถ๋ ฅ๋จ
eventlistener ์์์ ์ฐ๋ฉด e.currentTarget
Last updated