Skip to content

javascript_jquery_basic_3_3b

KyusungDev edited this page May 1, 2017 · 4 revisions

์ค‘์ฒฉ ํ•จ์ˆ˜์—์„œ this๋Š” ์™œ window ๊ฐ์ฒด๊ฐ€ ๋˜๋Š”๊ฐ€?

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ this ๊ฐ์ฒด๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•œ๋‹ค.
this ๊ฐ์ฒด๊ฐ€ ์„ค์ •๋˜๋Š” 3๊ฐ€์ง€ ๊ฒฝ์šฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  1. someThing.someFunction(arg1, arg2, argN)
  2. someFunction.call(someThing, arg1, arg2, argN)
  3. someFunction.apply(someThing, [arg1, arg2, argN])

์œ„ ์ƒํ™ฉ์—์„œ ๋ชจ๋“  this๋Š” someThing์ด๋‹ค.
ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ์„ ํ–‰ ๋ถ€๋ชจ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š”, ์ผ๋ฐ˜์ ์œผ๋กœ ๋ธŒ๋ผ์šฐ์ €์˜ global object์ธ window ๊ฐ์ฒด๊ฐ€ ๋ถ€๋ชจ๊ฐ€ ๋œ๋‹ค.

var std_obj = {
  options : { rows: 0, cols: 0 },
  activeEffect : "none",
  displayMe : function() {

    // the 'this' pointer is referring to the std_obj
    if (this.activeEffect=="fade") { }

    var doSomeEffects = function() {

      // the 'this' pointer is referring to the window obj, why?
      if (this.activeEffect=="fade") { }

    }

    doSomeEffects();   
  }
};

std_obj.displayMe();

์œ„ ์ฝ”๋“œ์—์„œ doSomeEffects()๋Š” ์‹ค์ œ๋กœ doSomeEffects.call(undefined);๋กœ ํ˜ธ์ถœ๋œ๋‹ค.
๋”ฐ๋ผ์„œ doSomeEffects์˜ ์Šค์ฝ”ํ”„ ๋‚ด๋ถ€์˜ this๋Š” window ๊ฐ์ฒด๊ฐ€ ๋œ๋‹ค.

Javascript โ€œthisโ€ pointer within nested function

ECMAScript ๊ทœ๊ฒฉ์—์„œ ์ผ๋ฐ˜ ํ•จ์ˆ˜ํ˜ธ์ถœ์˜ this ๋ฐ”์ธ๋”ฉ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋™์ž‘ํ•œ๋‹ค.

  1. strict mode์ผ ๊ฒฝ์šฐ thisValue(this)๋ฅผ thisArgument(์ˆจ์€ ์ธ์ž)๋กœ ์ง€์ •ํ•œ๋‹ค
  2. strict mode๊ฐ€ ์•„๋‹ˆ๊ณ , thisArguments(์ˆจ์€ ์ธ์ž)๋Š” null ๋˜๋Š” undefined ๋ผ๋ฉด,
  3. thisValue(this)๋ฅผ [[globalThis]]๋กœ ์„ค์ •ํ•œ๋‹ค. // ์ผ๋ฐ˜์ ์œผ๋กœ window ๊ฐ์ฒด
  4. thisArguments๊ฐ€ null ๋˜๋Š” undefined๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด thisValue๋ฅผ thisArgument๋กœ ์„ค์ •ํ•œ๋‹ค.

ECMAScript 2015 9.2.1.2 OrdinaryCallBindThis

๊ฐ์ฒด ์ดˆ๊ธฐํ™”์‹œ ์ฝœ๋ก (:)์„ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ ?

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ 1.2๋ถ€ํ„ฐ ๊ฐ์ฒด ์ด๋‹ˆ์…œ๋ผ์ด์ €๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ• ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹ค.
๊ฐ์ฒด ์ด๋‹ˆ์…œ๋ผ์ด์ €๋Š” ๊ฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๊ธฐ ์œ„ํ•œ ์ถ•์•ฝํ‘œ๊ธฐ๋ฒ•์ด๋‹ค.

๊ฐ์ฒด ์ด๋‹ˆ์…œ๋ผ์ด์ €๋Š” ์ด์šฉํ•œ ๊ฐ์ฒด ์ƒ์„ฑ ๋ฌธ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

var o = {
    r: 'some value',
    t: 'some other value'
};

์ถ•์•ฝํ‘œ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋ฉด ๊ธฐ๋Šฅ์ ์œผ๋กœ ์•„๋ž˜์™€ ๊ฐ™์ด ๊ธฐ๋Šฅ์ ์œผ๋กœ ๋™์ผํ•œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

What does ':' (colon) do in JavaScript?
Working with objects
Object initializer

Clone this wiki locally