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 - function, this 본문

Javascript

Javascript - function, this

보람- 2023. 8. 3. 18:00

목차

1. 함수 선언식과 표현식

2. 함수를 사용하는 방법

2-1 일반함수로 사용

    2-2 생성자 함수로 사용

 2-3 객체 메서드 할당

3. this 바인딩


 

 

1. 함수 선언식과 표현식

- 선언식

function a(){
    console.log('a')
}

- 표현식

const b = function (){
    console.log('b')
}

 

 

 

2. 함수를 사용하는 방법

 

2-1 일반함수로 사용

function foo(a, b) {
  console.log(this);
  // window객체
  return [a, b];
}
const a = foo(1, 2);
console.log(a);
//[1,2]

 

 

2-2 생성자 함수로 사용

function foo() {
  // this={}
  console.log(this);
  // return this
}
const a = new foo();

 

 

2-3 객체 메서드 할당

function foo(a, b) {
  console.log(this);
  // {method:f}
}

const bar = {
  method: foo,
};

bar.method(1, 2);

 

 

 

3. this 바인딩

- bind, call, apply

 

① bind

function foo(a, b) {
    // this={id='web7722}
  console.log(this);
  // window객체
}
foo(1, 2);

const bar = foo.bind({id:'web7722'});
// bind는 리턴값이 있어
/*
function(){
    this={id:"web7722"}
    console.log(this)
}
*/
bar()

 

※ 화살표 함수 사용

const foo = (a, b) => {
  console.log(this);
  return [a, b];
};
// foo();
//window객체

const c = new foo();

 


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

 

※ ES6 이후로 화살표 함수를 사용하게 되면  this 바인딩이 일어나지 않는다!

    → 한번 선언된 this가 바뀌지않는다는 것

 

 

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