function hello(name){
return `hello ${name}`;
}
const hello = function() {
console.log('hello');
}
console.log(hello);
function hello(name) {}
const hello = function() {}
hello();
hello2(); //error : hello2 is not function
//hello2가 뭔지는 알지만 함수인지는 모른다.
hello3(); //error : hello3 is not defined
//hello3 를 아예 찾을 수 없다.
//선언적 함수
function hello(){
console.log('hello')
}
//익명함수 : var 변수에 할당 , hoisting 가능
var hello2 = function(){
console.log('hello');
}
//익명함수 : const 변수에 할당, hoisting 불가능
const hello3 = function(){
console.log('hello3');
}
const sum = new Function('a','b','c','return a+b+c');
console.log(sum(1,2,3));
🧐 function과 new function의 차이점 ?
{
const a = 1;
const test = new Function('return a');
console.log(test());
// error: a is not defined
// new function으로 선언된 함수가 같은 범위에 있는 지역변수에 접근이 안된다.
}
global.a = 0;
{
const a = 1;
const test = new Function('return a');
console.log(test());
// 출력 : 0
}
global.a = 0;
{
const a = 1;
const test = new Function('return a');
console.log(test());
// 출력 : 0
}
{
const a = 2;
const test = function() {
return ;
};
console.log(test());
// 출력 : 2
// 같은 지역변수 a를 사용함
}
// 매개변수는 소괄호에 넣어서 전달한다.
// 함수의 바디는 중괄호에 정의한다.
const hello = () => {
console.log('hello');
};
// 변수에 할당해서 쓸 수 있지만 항상 익명함수가 된다.
// 선언적 방식으론 쓸 수 없게된다.
//매개변수가 하나일 때, 괄호를 생략할 수 있다.
const hello2 = name => {
console.log('hello2', name);
};
const hello3 = (name,age) => {
console.log('hello3',name,age);
};
const hello4 = name => {
return `hello ${name}`;
};
//!! return 도 생략 가능하다 !!
const hello5 = name => `hello ${name}`;
// function Person이 여러 개의 객체를 만들 수 있는 이유
// ✨ Person이라는 function이 자기 자신 객체를 가리키는 this를 만들어 내기 때문
// 🚨 arrow function 은 this를 만들지 않기 때문에, 이를 이용해서 객체를 만들 수 없다.
function Person(name,age){
console.log(this);
// 출력 : Person {}
this.name=name;
this.age=age;
}
const p = new Person('doyeon',24);
console.log(p, p.name, p.age);
// 출력 : Person { name:'doyeon', age: 24} 'doyeon' 24
const a = new Person('woong',3);
console.log(a, a.name, a.age);
// 출력 : Person { name:'woong', age: 3} 'woong' 3
const Cat = (name,age) => {
console.log(this);
this.name = name;
this.age = age;
// error : Cat is not a constructor
// 그 안에 this를 가지고 있지 않기 때문에 객체를 생성할 수 없다.
}
const c = new Cat('냥이',3);
function plus(base){
return function(num){
return base + num;
}
}
const plus5 = plus(5);
// base : 5
console.log(plus5(10);)
// num : 10
// 출력 : 15
const plus7 = plus(7);
console.log(plus7(8));
// 출력 : 15
function hello(c){
console.log('hello');
c();
}
hello(function(){
console.log('콜백');
});
// 출력 :
// hello
// 콜백