TIL no.10

손병진·2020년 7월 22일
0

TIL

목록 보기
10/22

함수

function

  • 선언적 function
function hello1(){
	console.log('hello1');};

console.log(hello1, typeof hello1); // [Function: hello1] 'function' 출력
// 함수도 객체의 한종류

function hello2(name){
	console.log('hello', name);};

function hello3(name){
	return `hello3 ${name}`;}; // template string
console.log(hello3('Mark')); // hello3 Mark 출력

  • 익명 함수를 만들어 변수에 할당
const hello1 = function(){
	console.log('hello1');};
console.log(hello1, typeof hello1); // [Function: hello1] 'functino' 출력

const hello2 = function(name){
	console.log('hello2', name);};

const hello3 = function(name){
	return `hello3 ${name}`;};

  • 두 방식의 차이
// var hello2; // hoisting 현상
// console.log(hello2); // undefined 출력

hello1(); // hello1 출력
hello2(); // error: hello2 is not a function
hello3(); // error: hello3 is not defined

function hello1(){
	console.log('hello1');}

var hello2 = function(){
	console.log('hello2');}

const hello3 = function(){
	consoloe.log('hello3');}

생성자

  • const hello = new Function();
    (자주 쓰이지는 않는다)
const sum = new Function('a','b','c','return a+b+c');
console.log(1,2,3); // 6 출력

  • function / new Function 차이점
// global.a = 0 // global 값이 new Function a 값으로 간다
{
	const a = 1;
  	const test = new Function('return a'); // const a 값을 받지 않는다
  	console.log(test()); // error: a is not defined
} 

	const a = 2;
  	const test = function(){return a;}; // const a 받아온다
  	console.log(test()); // 2 출력

  • arrow function(es6)
const hello1 = () => {console.log('hello1');};

const hello2 = name => { // 매개변수가 하나일때 괄호 생략 가능
  console.log('hello2', name);};

const hello3 = (name, age) => {
  console.log('hello2', name, age);};

const hello4 = name => {
  return `hello4 ${name}`;}; // return

const hello5 = name => `hello5 ${name}`; // {return } 생략 가능
profile
https://castie.tistory.com

0개의 댓글