1급 객체란?
- 변수에 할당할 수 있습니다.
- 함수의 매개변수로 전달할 수 있습니다.
- 함수의 반환값으로 사용할 수 있습니다.
Java와 JavaScript 비교
1. 변수에 할당할 수 있습니다.
java
public class Main {
public static void hello(){
System.out.println("Hello World");
}
public static void main(String[] args) {
Object a = hello; // 메서드를 변수에 할당 불가능
}
}
javascript
const hello = function() {
console.log("Hello World");
}
2. 함수의 매개변수로 전달할 수 있습니다.
java
public class Main {
public static void hello(){
System.out.println("Hello World");
}
public static void print(Object func) {
func();
}
public static void main(String[] args) {
print((Object) hello) // static 메서드를 함수 매개변수로 전달 불가능
}
}
javascript
const hello = function() {
console.log("Hello World");
}
function print(func) {
func();
}
print(hello);
3. 함수의 반환값으로 사용할 수 있습니다.
javascript
const hello = function() {
console.log("Hello World");
return function() {
console.log("Hello World 22");
}
}
const hello2 = hello();
hello2();
Java는 람다식이나 익명 클래스로 1급 객체 역할을 수행할 수 있습니다.
Share article