1. new 함수(); : 생성자 함수
생성자 함수의 기본적인 특징을 다음과 같은 코드를 통해서 살펴보자.
function Person(name, age){
console.log(this);
this.name = name;
this.age = age;
}
const p = new Person('Mark', 37);
const a = new Person('Anna', 31);
console.log(p, p.name, p.age,);
console.log(a, a.name, a.age);
[Running]
Person {}
Person {}
Person { name: 'Mark', age: 37 } Mark 37
Person { name: 'Anna', age: 31 } Anna 31
생성자 함수는 'this'를 이용하여 위와 같이 각 매개변수의 값들을 입력하고 출력할 수 있다.
그렇다면 arrow 함수는 어떨까?
const Cat = (name, age) => {
console.log(this);
this.name = name;
this.age = age;
}
const c = new Cat('냥이', 3);
[Running]
const c = new Cat('냥이', 3);
^
TypeError: Cat is not a constructor
arrow 함수는 생성자가 될 수 없다! = 객체 생성이 되지 않음을 알 수 있습니다.
2. 함수 안에서 함수를 만들어 리턴
덧셈 함수를 다음과 같은 형태로 만들 수 있다.
function plus(base){
return function(num){
return base + num;
};
}
const plus5 = plus(5);
console.log(plus5(10));
const plus7 = plus(7);
console.log(plus7(8));
[Running]
15
15
plus 함수의 리턴 값에 더하는 기능의 함수를 넣어 덧셈 함수를 구현하였다.
3. 함수를 호출할 때, 인자로 함수를 사용
함수의 인자를 함수로 사용할 수 있다.
function hello(callback){
console.log('hello');
callback();
}
hello(function(){
console.log('콜백');
});
[Running]
hello
콜백
hello에 '콜백'을 출력하는 함수를 인자로 넣어서 실행시켰더니
먼저 'hello' 가 출력된 다음, 인자로 들어가 있는 함수에 의해 '콜백'이 출력되었다.
'JavaScript' 카테고리의 다른 글
JavaScript기초(22)_객체(2) (0) | 2021.10.16 |
---|---|
JavaScript기초(21)_객체(1) (0) | 2021.10.15 |
JavaScript기초(19)_함수(5) (0) | 2021.10.13 |
JavaScript기초(18)_함수(4) (0) | 2021.10.12 |
JavaScript기초(17)_함수(3) (0) | 2021.10.11 |
댓글