본문 바로가기

Javascript

[JavaScript] 함수

function

//function
//이름이 hello인 함수

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

console.log(hello, typeOf hello);
// 출력 : [function: hello] 'function'
// 함수의 매개변수
//함수를 호출 할 값을 지정

function hello2(name) {
	console.log('hello2', name)
}
// 함수의 리턴
// 함수를 실행하면 얻어지는 값

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

console.log(hello3('Hyewon'));

 

 

const hello = function( ) { }

함수를 만들 때 사용하는 키워드

 

const hello1 = function() {
	console.log('hello');
};
console.log(hello1, typeOf hello1);
// 함수의 매개변수
// 함수를 호출할 때 값을 지정

const hello2 = function(name) {
	console.log('hello2', name);
}
// 함수의 리턴
// 함수를 실행하면 얻어지는 값

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

 

 

function 과 new Function(); 

global.a = 0; // 전역변수

{
	const a =1;
    const test = new Function('return a');
    console.log(test());
} // 0이 출력됨

{
	const a = 2;
    const test = function() {
    	return a;
    }
    console.log(test());
} // 2가 출력됨

 

( ) => { } : arrow function (es6)

const hello1 = () => {
	console.log('hello1');
};

 

  • 선언적 함수 X → 항상 익명함수로 사용
  • hello1에 담아서 사용하는 형태

 

// 매개변수
// 호출할 값을 지정

const hello2 = name => {  // (name) 이라고 해도 상관 없음
	console.log('hello2', name);
};

const hello3 = (name, age) => {  // 매개변수를 두개이상 사용할 땐 괄호 필수
	console.log('hello3', name, age);
};
// 함수의 리턴값
//함수를 실행하면 얻어지는 값

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

const hello5 = name => `hello5 ${name}`;

 

 

new 함수(); : 생성자 함수

function Person(name, age) {
	console.log(this); // this : 객체가 만들어졌을 때 객체를 가르키는 용도로 사용됨
	this.name = name;
    this.age = age;
}

const p = new Person('hyewon', 24);
console.log(p, p.name, p.age);

const a = new Person('Mark', 37);
console.log(a, a.name, a.age);

 

함수 안에서 함수 만들어 리턴

function plus(base) {
	return function(num){
    	return base + num;
    }
}

const plus5 = plus(5);
console.log(plus5(10)); // 15 출력

 

함수를 호출할 때, 인자로 함수를 사용

function hello(c) {
	console.log('hello'); //hello 출력됨
    c();
}

hello(function() {
	console.log('콜백');
});  //콜백 출력됨

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Javascript' 카테고리의 다른 글

[JavaScript] 객체 objet  (0) 2022.04.05
[JavaScript] 반복문  (0) 2022.04.04
[JavaScript] 조건문  (0) 2022.04.04
[JavaScript] 시작하면서  (0) 2022.03.29