자바스크립트 기초 (+)

김주언·2022년 2월 23일

자바스크립트

목록 보기
2/8
post-thumbnail

JavaScript Essentials

즉시실행 함수 IIFE

const a = 7;
// 1번째 유형
(function () {
  console.log(a * 2);
})();

// 2번째 유형
(function () {
  console.log(a * 2);
}());

// 콘솔에 14 출력됨

타임아웃 함수

setTimeout(함수, 시간) : 일정 시간 후 함수 실행

setTimeout(function () {
  console.log('setTimeout');
}, 3000);  //ms 단위 즉 3초

setTimeout(() => {
  console.log('setTimeout with ArrowFunction');
}, 3000);

clearTimeout() : 설정된 Timeout 함수를 종료

const timer = setTimeout(() => {
  console.log('setTimeout with ArrowFunction');
}, 3000);

const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
  clearTimeout(timer);
});

→ 3초 이내에 화면의 h1을 클릭하면 3초가 지난후에도 setTimeout의 내용이 실행되지 않는다.

setInterval & clearInterval

const timer = setInterval(() => {
  console.log('setInterval with ArrowFunction');
}, 3000);

const h1El = document.querySelector('h1');
h1El.addEventListener('click', () => {
  clearInterval(timer);
});

콜백 함수

: 함수의 인수로 사용되는 함수

함수의 실행위치를 보장하는 방식으로 많이 활용된다

실행위치 보장 예제

function timeout() {
  setTimeout(() => {
    console.log('test');
  }, 2000);
}

timeout();
console.log('done');

위의 코드 실행시 콘솔에

done

test

순서로 출력됨

function timeout(callBack) {
  setTimeout(() => {
    console.log('test');
    callBack();
  }, 2000);
}

timeout(() => {
  console.log('done');
});

위의 코드를 실행하면 콘솔에

test

done

순서로 정상적으로 출력된다.

클래스

생성자 함수

function User(first, last) {   // ParsecalCase 방식 지켜줄것
  this.firstName = first;
  this.lastName = last;
}

const jueon = new User('jueon', 'kim');
console.log(jueon);

위와 동일한 동작을 하는 ES6 Classes - class 키워드, constructor 사용

class User {
  constructor(first, last) {
    this.firstName = first;
    this.lastName = last;
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const user1 = new User('user', '1');
console.log(user1);
console.log(user1.getFullName());

프로토타입

프로토타입 함수를 사용하지 않을 경우

const jueon = {
  firstName: 'jueon',
  lastName: 'kim',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};

const user1 = {
  firstName: 'user',
  lastName: '1',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};

const user2 = {
  firstName: 'user',
  lastName: '2',
  getFullName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};

console.log(jueon.getFullName());
console.log(user1.getFullName());
console.log(user2.getFullName());

getFullName()이라는 함수를 사용하기 위해 각 객체마다 할당해주고 이는 메모리를 각각 다른 공간을 차지하며 올라가기 때문에 메모리 누수를 유발한다.

프로토타입 활용

function User(first, last) {
  this.firstName = first;
  this.lastName = last;
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`;   // 백틱!!
};

const jueon = new User('jueon', 'kim');
const user1 = new User('user', '1');
const user2 = new User('user', '2');

console.log(jueon);
console.log(user1.getFullName());
console.log(user2.getFullName());

위의 경우의 getFullName()함수는 프로토타입으로 선언된 함수를 참조하는 방식

→ 메모리의 효율적 사용이 가능하다.

this

this

일반 함수는 호출 위치에 따라 this를 정의

화살표 함수는 자신이 선언된 함수 범위 내에서 this 정의

예제 1

const user1 = {
  name: 'user1',
  normal: function () {
    console.log(this.name);
  },
  arrow: () => {
    console.log(this.name);
  },
};

user1.normal();   // user1
user1.arrow();    // undefined

const user2 = {
  name: 'user2',
  normal: user1.normal,  //함수 호출이 아니라 선언! 괄호사용 주의할것
  arrow: user1.arrow,
};

user2.normal();   // user2
user2.arrow();    // undefined

예제 2

function User(name) {
  this.name = name;
}

User.prototype.normal = function () {
  console.log(this.name);
};

User.prototype.arrow = () => {
  console.log(this.name);
};

const user1 = new User('user1');

user1.normal();     // user1
user1.arrow();      // undefined

예제 3

const timer = {
  name: 'timer name',
  timeout: function () {
    setTimeout(function () {
      console.log(this.name);
    }, 2000);
  },
};

timer.timeout();

위의 코드를 실행하면 콘솔에 undefined 출력된다.

→ 현재 this는 일반함수 내에서 정의되어 있음. 일반함수는 호출위치에 따라 this를 정의하는데, 위의경우에는 해당 함수가 setTimeout의 내부로직으로 콜백이 되어서 어딘가에서 실행됨..

→ 위 timer.timeout()을 실행하여 해당 객체의 name속성을 출력하고 싶다면 화살표 함수로 수정해줘야한다

const timer = {
  name: 'timer name',
  timeout: function () {
    setTimeout(() => {
      console.log(this.name);
    }, 2000);
  },
};

timer.timeout();

화살표 함수는 자신이 선언된 함수 범위 내에서 this를 정의하기 때문에 timer.timeout()을 수행하면 timer 객체의 name 속성이 출력된다.

화살표 함수는 자신이 선언된 함수 범위내에서 this를 정의한다.

setTimeout(() => { console.log(this.name); }, 2000);

에서 setTimeout()이라는 함수는 timeout : function () {} 의 내부에 있는 함수이다. 그리고 timeout 함수는 일반 함수이기 때문에 화살표함수에서의 this → 일반함수에서의 this로 흐름이 흘러가서 (??)

결론적으로 timer.timeout() 을 호출하게 되면 일반함수의 this가 호출위치에 따라 결정되는 규칙을 따라 화살표함수의 this는 timer객체가 되는 것이다.

뭔,.,뭔소리임?

profile
학생 점심을 좀 차리시길 바랍니다

0개의 댓글