Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

Javascript - this, bind, static, closure 본문

Javascript

Javascript - this, bind, static, closure

보람- 2023. 7. 13. 17:12

목차

1. this

2. bind

3. static

4. closure


 

 

 

1.this

 

  • 전역스코프에서의 this
console.log(this);

- 전역 스코프에서 this를 console하면 window 객체를 가리킨다.

 

 

  • 객체에서의 this
({
  a: 1000,
  checkThis() {
    console.log(this);
  },
}).checkThis();

- 객체안에서의 this를 console하면 자기자신을 보여준다.

 

 

  • class내에서의 this
class Test {
  checkThis() {
    console.log(this);
  }
  checkThisArrow = () => {
    console.log(this);
  };
}

const test = new Test();

test.checkThis();
test.checkThisArrow();

- test 인스턴스를 사용해 두 함수를 불러오면 둘다 class 자체를 뜻한다. (인스턴스 객체)

 

 

  • function에서의 this
function TestFunc() {}
TestFunc.prototype.checkThis = function () {
  console.log(this);
};
TestFunc.prototype.checkThisArrow = () => {
  console.log(this);
};

const testFunc = new TestFunc();
testFunc.checkThis();
testFunc.checkThisArrow();

 

- 그냥 function인 경우 : prototype에 function 

- 화살표 함수일 경우 : 전역스코프이기 때문에 window 객체를 보여준다.

   → 화살표 함수는 bind가 안먹힌다!!!

 

 

 

2. bind 

test.checkThis.bind(window)();
test.checkThis.bind(testFunc)();

- bind()를 주면 this를 다시 정의해준다.

   → (window)를 쓰면 window객체를 보여준다. 

- 다시 bind(testFunc)()을 주면 원래 test로 돌아간다.

 

- bind는 원본을 건드리지않고 this만 바꿔서 재정의해주는것이다.

- 호출해서 리턴으로 함수를 반환해주므로 bind는 고차함수이다.

 

- 화살표 함수에는 this가 무조건 고정되어 있어서 bind를 써도 수정되지않는다.

  → 그래서 위에 function안에 chekThisArrow함수의 this가 window로 나왔던것!!!

 

 

 

3. static

class Test {
  name;
  #age;
  static area;

  constructor() {
    this.func = function () {};
  }
  checkArea() {
    console.log(this);
  }
}

const test = new Test();
console.log(test);

function TestFunc() {
  this.func = function () {};
}
TestFunc.area = "Hi";
console.log(TestFunc.area);

- class Test의 key로 name, #age, static area 를 주었는데 console.log하면 Test의  key에 area는 뜨지않는다.

 

console.dir(Test);

- console.dir로 Test를 보면 그때서야 area가 보인다.

  → static은 class 자체에서만 사용이 가능하다!

 

Object.keys();
Object.values();
Date.now();

 

- static은 클래스자체에서 포함되어있는 메서드, 변수라고한다. (정적 = static)

  → 생성자 함수 자체에 포함된 메서드 (프롬퍼티와 같다)

 

 

 

4. closure

function closure() {
  let a = 1234;
  return () => {
    return a;
  };
}

const tempClosure = closure();
console.log(tempClosure());
console.dir(tempClosure);

- 원래는 a의 값은 함수가 실행되고 끝나면 스택이 빠지면서 a가 사라져야하는데,

  return값으로 a를 쓰고있어서 없어지지 않고 스택에 남아있어서 a값을 불러올수는 있지만 수정은 불가능하다!

  → 자체적인 private로 볼수있다(캡슐화)

- 반환받은 함수를 tempClosuer가 가지고있고, tempClosuer()로 반환받은 함수를 다시 불러올수가있다!

  → 고차함수

 


 오늘의 포인트와 남겨두기 ★

 

※ { 스코프 } 에 소괄호 ()로 묶어주면 객체로 인식한다!

※ 최상위는 prototype은 Object이고, 그위는 없어서 null로 나온다.

※ 용어정리해서 외우기

 

 

*** 앞으로 백엔드, 서버를 배우고 블록체인까지 배워 개발자가 되는 그날까지 화이팅!!!!!!!!!!

** 목표에 대해 생각하자!!!!!

* 만들고 싶은것의 흐름을 생각해보기