20일차 JavaScript 함수, this, 연산자, 반복문

변승훈·2022년 4월 29일
0

※과제로 인하여 정리 기간이 늦어졌습니다..
수업내용 위주의 정리입니다.

1. 함수

1-1. 화살표 함수

화살표 함수는 익명함수이다. 함수 표현이며 호이스팅이 되지 않는다!

const hello = () => {
  return 'hello';
}
  • 간소화: return은 생략이 가능하다. 단, return이 하나만 있을 때만 가능하다!
/*
const hello = () => {
	return 'hello'
	};
*/

// 1.
const hello = () => 'hello';
console.log(hello());

// 2.

const hello = () => console.log('hello');
hello();
  • 객체데이터를 사용할 때는 소괄호로 감싸줘야 한다.
const hello = () => ({});
console.log(hello());


// 객체데이터 변수의 이름 간소화
/*
	function reFunc(a, b) {
    return {
      a: a,	//	a로 간소화 가능
      b: b	//	b로 간소화 가능
      }
    };
*/
//

function reFunc (a, b) {
  return { a, b }
}
const reFunc = (a, b) =>({a, b});

console.log(reFunc('hello', 'world'));
  • 매개변수가 하나이면 매개변수 좌, 우에 있는 소괄호( )는 생략이 가능하다
// const hello = (message) => `hello ${message}`
const hello = message => `hello ${message}`
console.log(hello('world'))

/*
divEl.addEventListener('click', function (event) {

})
*/
divEl.addEventListener('click', event => {

})

1-2. this

  • thisthis가 사용된 유효범위(scope)에 해당되는 객체를 참조한다.
  • 일반 또는 화살표 함수에서 정의가 다르다!
  • 일반 함수에서 this는 호출되는 위치에서 정의된다!
console.log(this);  // window객체가 출력

// this: 아래에 있는 Hun을 참조한다.
// 아래의 일반함수에서의 this는 정확하게 정의를 내릴 수 없다.
// 호출되는 위치에서 정의가 되기 때문이다.(console.log(Hun.getNameAndAge))
// 1. 일반함수에서는 호출되는 위치에서 this가 정의된다. 그래서 this가 뭔지 정확하게 알 수 없다.
const Hun = {
  name: 'Hun',
  age: 27,
  email: 'theseisemail.com',
  phone: '01012345678',
  getNameAndAge: function () {
    return [this.name, this.age];
  }
}

const amy = {
  name: 'Amy',
  age: 22
}


console.log(Hun.getNameAndAge())  // ['Hun', 27]
console.log(Hun.getNameAndAge.call(amy))  // ['Amy', 22], Hun.getNameAndAge 함수를 amy객체로 호출해라
  										  //-> this가 amy를 바라보게됨
  • 화살표 함수에서 this는 자신이 선언된 함수(렉시컬) 범위에서 정의된다!
    +) 속성 안에 함수를 메소드라 한다.
// 2. 화살표함수 안에서의 this: 선언된 위치에서 정의가 된다.
// 속성 안에 함수를 메소드라 한다.
function wrapper() {
  this.name= 'Wrapper';
  this.age= 99;
  
  const Hun = {
    name: 'Hun',
    age: 27,
    email: 'theseisemail.com',
    phone: '01012345678',
    getNameAndAge: () => {	// 메소드
      return [this.name, this.age];
    }
  }

  const amy = {
    name: 'Amy',
    age: 22
  }


console.log(Hun.getNameAndAge.call(amy))  // ['', undefined]
}

wraaper();  // ['Wrapper', 99]
  • this 예제 1.
    call, apply: 호출용, apply는 인수들을 나열하지 않고 배열로 묶고 나열한 후 전달해 주는 방식이다.
    bind: 연결용
const hun = {
  name: 'Hun'
}
const mari = {
  name: 'Mari',
  getName(age) {
    return `${this.name} is ${age}`
  }
}

// call
console.log(mari.getName.call(hun, 27))	// Hun is 27

// apply
console.log( mari.getName.apply(hun[27]))	//  is undefined

// bind
const hunsGetName = mari.getName.bind(hun)
console.log(hunsGetName(27)) // Hun is 27

  • 예제 2.
const userA = {
  isValid: true,
  age: 85,
  // 1번
  getAge: function () {
    return this.age
  }
}

const userB = {
  isValid: false,
  age: 22,
  // 2번
  // getAge: function () {
  getAge: () => {
    return this.age
  }
}

console.log(userA.getAge) // 함수가 호출
console.log(userA.getAge()) // 85

// call, bind
// getAge: function () { 사용 시
console.log(userB.getAge.call(userA)) // 1번, 85

// 화살표 함수,   getAge: () => { 사용 시
console.log(userB.getAge.call(userA)) // 2번, undefined, 화살표 함수 때문에 범위가 window가 된다. 
									  // window에 있는 age를 출력해서 undefined가 나오게 된다.


const userC = {
  isValid: true,
  age: 85,
  getAge: function () {
    setTimeout( function () {
      console.log(this.age)
    }, 1000)
  }
}
userC.getAge() // undefined, 
			   // 호출되는 위치는 setTimeout, this의범위는 setTimeout함수이다.
			   // setTimeout함수안에 들어가서 뒷단으로 넘어가서 호출하기에 범위가 window일 확률이 높다

// 화살표 함수면 getAge()까지 범위이기 때문에 85가 출력 된다

1-3. 재귀(recursive) 함수

내 자신 안에서 나를 실행 시킨다.
자기 자신을 자기 자신 안에서 호출하는 것, 무한 반복이 되며 재귀함수 사용 시 항상 종료 조건이 있어야 한다.
깊은 복사에서 참조형 안에 참조가 없을 때 까지 재귀함수가 사용된다.

let i = 0;

function abc() {
  console.log(i)
  i += 1;
  if (i < 10) {
    abc();
  }
}
abc();

2연산자

2-1. 비교연산자

연산자이름
==동등
!=부등
===일치
!==불일치
a > ba가 b보다 크다
a >= ba가 b보다 크거나 같다
a < ba가 b보다 작다
a <= ba가 b보다 작거나 같다

2-2. 논리연산자

a && b 그리고(And)

  • 가장 먼저 찾은 Falsy를 반환한다. Falsy를 찾지 못하면 마지막 값을 반환한다.

a || b 또는(Or) :

  • 가장 먼저 찾은 Truthy를 반환한다. Truthy를 찾지 못하면 마지막 값을 반환한다.

!a 부정(Not) :

  • a가 Truthy면 false로, Falsy면 true로 바뀐다.

2-3. 삼항 연산자

조건 ? 2항 : 3항
조건이 truthy면 2항 Falsy면 3항이 실행되는 연산자 이다.

3. 반복문

3-1. switch statement

조건이 어떤 값으로 딱 떨어질 때 사용한다.
switch문 -> if조건으로 변경해서 사용할 수 있지만
if조건 -> switch문으로 완벽하게 바꾸는 것을 보장할 수 없다.

const inputEl = document.querySelector('input')

inputEl.addEventListener('keydown', event => {
  if (
    event.key === 'Enter' || 
    event.key === 'Escape'
  ) {
    console.log('Wow')
  } else {
    console.log('eieieig')
  }
})

switch (event.key) {
  case: 'Enter' :
  case: 'Escape' :
    console.log('Wow')
    break;
  case: 'Shift':
    cosoel.log('shift')
    break;
  default:
    console.log('eieieig')
}

3-2. for

for(시작;종료;변화){

}

for(i = 0; i<10 ; i += 1) {
	console.log(i)
}

3-3. for of

배열 반복 시 사용한다.

const users = [
{ name: 'Hun', age: 27},
{ name: 'Hyun', age: 18},
{ name: 'Jeung', age: 2}
]

for (const user of users) {
  console.log(user);
}

for (let i = 0; users.length; i += 1) {
  console.log(users[i]);
}

3-4. for in

객체 반복 시 사용한다.

const hun = {
  name: 'Hun',
  age: 27,
  isValid: true
}

for (const key in hun) {
  console.lof(hun[key])
}

3-5. while

조건이 falsy면 0번 실행한다.

let i = 0;  // 시작
while (i<3) { // 종료
  console.log(i)
  i += 1; //  변화
}

3-6. do while

조건이 falsy여도 한 번 실행한다.

let j = 0;  // 시작
do {
  console.log(j);
  j += 1  // 변화
} while (false) // 종료
profile
잘 할 수 있는 개발자가 되기 위하여

0개의 댓글