티스토리 뷰

2019.07.31(수)

Java Script 함수 호출, 객체, 배열 사용

 

  • Ex01
// Ex01

// 자바스크립트는 함수 오버로딩이 성립되지 않는다.
function f1() {
    console.log('나는야 f1()-1');
}

function f1(a) {
    console.log('나는야 f1()-2');
    console.log(a); 
}

function f1(a, b) {
    console.log('나는야 f1()-3');
    console.log(a, b);
}
// 3개 모두 f1(a, b)의 함수가 호출이 된다.
// 즉, 가장 마지막에 컴파일 되었던 함수만 남고 나머지는 무시(제거)된다.
f1();
console.log('------------');
f1(5);
console.log('------------');
f1(5, 10);

Ex01 실행결과

  • Ex02
// Ex02

function f1(a, b) {
    console.log(a, b);
}
f1();
f1(10);
f1(10, 20);
f1(10, 20, 30); // 기본적으로 잘못된 코드이지만 문법적으로는 문제 없이 작동한다.
console.log('-----------------------------------');

// 함수 인수에 초기화
// a=10, c=99 : 인수전달이 되지 않았을 때 default를 10으로 하겠다.
// 전달을 받으면 전달받은 값으로 사용하겠다.
function f2(a=10, b, c=99) {
    console.log(a, b, c);
}
f2();
f2(20, 30, 40);
console.log('-----------------------------------');

// 인수로 함수 전달
// 함수도 변수 처럼 인수 안에 default 값으로 함수 선언을 해서 사용 할 수 있다.
function f3(f = () => console.log('코끼리') ) {
    f();
}

f3(() => {
    console.log('호랑이');
}); 
f3();
console.log('-----------------------------------');

//
function f4(f) {
    console.log('나는야 f4()');
    console.log(f);
}

function f5() {
    console.log('나는야 f5()');
}

function f6() {
    console.log('나는야 f6()');
    return 100;
}
// 아래 세 가지의 방식은 전혀 다른 방식이다.
f4(f5); // 함수 코드 자체를 넘기는 것이다, 함수를 써 먹을 수 있다. (인수 전달이 있는 것이다.)
console.log('------------');
f4(f5()); // 함수 f5()를 call 시키는 것이다.(인수 전달이 없는 것이다.), f5() call 먼저 실시 후 f4() call
console.log('------------');
f4(f6()); // f6()에 return을 받아서 인수 전달로 사용이 되고 있다.
console.log('-----------------------------------');

//
function f7() {
    return {    // 이 함수는 객체를 return 한다.
        a : 10,
        b : '독수리',
    }
}

function f8() {
    return f7;  // 함수 자체를 return
}

function f9() {
    return f7();    // 함수 f7()을 call 했을 때의 f7()의 return 값을 받는다.
}

// f8()은 함수 자체를 받기 때문에 f8()과 f7()은 동일하다고 생각하면 된다.
// 그렇기 때문에 f8()을 call 하게 되면 객체를 리턴한다.
const obj = f9(f8());
console.log(obj.a, obj.b);
// f9()은 함수 f7()의 객체를 return 하기 때문에 받아서 사용 가능하다.
const obj1 = f9();
console.log(obj1.a, obj1.b);

Ex02 실행결과

  • Ex03
// Ex03

let obj = {
    a : 10,
    b : 20,
}
console.log(obj);

obj.a = 30; // 데이터 갱신
console.log(obj);

// 객체의 동적 속성 추가
obj.c = 30; // 없는 속성이지만 속성이 추가 된다.
console.log(obj);

// 객체의 동적 속성 제거 
delete(obj.b); // b의 속성을 제거
console.log(obj);

Ex03 실행결과

  • Ex04
// Ex04

const obj = {
    a : 1,
    b : 2,
    c : 3,
}

const obj1 = {
    a : 1,
    b : {
        valueB : 2
    },
    c : {
        valueC : 3
    },
}

// obj 객체 안의 값 변경을 불가능 하게 하고 싶다면?
// 안에 있는 a,b,c 모두 동결 된다.
Object.freeze(obj);

// obj가 const 인데 값이 변경이 되지 않아야 되는 것이 아닌가?
obj.a = 10;
console.log(obj);

// 동결 되었기 때문에 수정 불가
obj.b.valueB = 200;
console.log(obj);

// a 하나만 동결 시키고 싶다면 : 가능하다.
obj.c.valueC = 300;
console.log(obj);

// 동결을 해제 하기 위해 아해의 방법을 사용하면 된다.
// 시간이 된다면 아래의 방법 해보기
// Object.defineProperty;  // 1개
// Object.defineProperties(obj.b, obj.c);  // 2개

Ex04 실행결과

  • Ex05
// Ex05

// 1.
// 편의상 한 줄로 처리
obj0 = { name : '호랑이', age : 20, salary : 200, }
obj1 = { name : '코끼리', age : 21, salary : 210, }
obj2 = { name : '독수리', age : 22, salary : 220, }
obj3 = { name : '코뿔소', age : 23, salary : 230, }
obj4 = { name : '하아마', age : 24, salary : 240, }

// 이렇게 객체가 여러개 일 경우에 이 객체들을 배열로 관리
const arr = [];
arr.push(obj0);
arr.push(obj1);
arr.push(obj2);
arr.push(obj3);
arr.push(obj4);

console.log(arr);
console.log('------------------------------------');

// 배열 0번 안에 들어있는 age와 salary의 합을 sum이라는 속성을 만들고자 한다
// 객체 안에 함수에서 객체 안의 속성을 사용 하려고 한다면 this를 사용해야 한다.
// arr[i]에 getsum과 sum을 추가
// 아래의 fuction()을 람다식으로는 지원 불가이기 때문에 error가 발생한다.
for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].getSum = function() { return this.age + this.salary };   // 동적으로 함수 삽입
    arr[i].sum = arr[i].getSum(); // 동적으로 sum 삽입
}
console.log(arr);

// 아래와 같이 일일이 넣어줘도 된다, 위와 동일
/*let sum = arr[0].age + arr[0].salary
// 위 결과 값을 속성 추가
arr[0].sum = sum; */

console.log('------------------------------------');

// 2.
// 내용 종합
// 객체 안에서 객체의 프로퍼티(멤버)에 접근하려면 함수든 변수든 모두 this를 사용해서 접근을 해야한다.
// this를 사용하지 않고 접근하면 error이 발생한다.
obj = {
    a : 10,
    f1 : function() {
        console.log('나는야 f1()');
        console.log(this.a);
    },
    f2 : function() {
        this.f1();
    },
}

obj.f2();

Ex05 실행결과

  • Ex06
// Ex06

// 이와 같이 코드를 작성한다면 Ex05 보다 좀 더 유연하게 코드를 작성 할 수 있다.
// 틀
obj = {
    a : 10,
    b : 20,
    f1 : function() {

    },
    f2 : function() {

    },
}

// 활용
function func(a, b) {
    return {    // 객체를 리턴하겠다는 의미이다.!!
        a : a,
        b : b, 
        f1 : function() {
            return this.a + this.b;

        },
        f2 : function() {
            return this.a - this.b;
        },
    }
}

// 아래 소스 이해하고 활용하기 
const arr = [];
arr.push(func(10, 20));
arr.push(func(30, 40));
arr.push(func(50, 60));
arr.push(func(70, 80));
console.log(arr[0].a);
console.log(arr[0].b);
console.log(arr[0].f1());
console.log(arr[0].f2());

Ex06 실행결과

  • Ex07
// Ex07

// 배열과 관련된 속성or함수

const arr = [3, 4, 1, 2];
console.log(arr.length);    // 객체의 길이 출력 속성
console.log(arr.sort());    // 배열의 값 정렬 함수(오름차순)

// sort()를 사용자에 맞게 사용하기
// 내림차순으로 정렬하기
arr.sort(function(a, b) {
    return b-a;
});

console.log(arr);

console.log('--------------------');

// - 값이 양수라고 생각을 하고 정렬을 하고 싶다.
// sort() 를 정의해서 사용하기
const arr1 = [-3, -4, 1, -2];

arr1.sort(function(a, b) {  // 절대값 오름차순
    let x = Math.abs(a);
    let y = Math.abs(b);
    return x-y;
});

console.log(arr1);
arr1.sort(function(a, b) {  // 절대값 내림차순
    let x = Math.abs(a);
    let y = Math.abs(b);
    return y-x;
});

console.log(arr1);

console.log('--------------------');

// 객체 3개를 가지고 있는데 객체 멤버의 값을 가지고 정렬을 하고 싶다.
// ar배열에 있는 객체들의 a 멤버를 통한 정렬
const ar = [{a:10, n:'김'}, {a:5, n:'박'}, {a:15, n:'최'}]    
console.log(ar);
ar.sort(function(obj1, obj2) { // 객체를 인수로 받는다.
    return obj1.a - obj2.a;
});
console.log(ar);

Ex07 실행결과

  • Ex08
// Ex08

// 간단한 연습문제
// 합계로 정렬하기

const dog = { name:'강아지', kor:10,eng:20,mat:30, };
const cat = { name:'고양이', kor:40,eng:50,mat:60, };
const tur = { name:'거북이', kor:70,eng:80,mat:90, };

const arr = [dog, cat, tur];

for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].getSum = function() { return this.kor + this.eng + this.mat };   // 동적으로 함수 삽입
    arr[i].sum = arr[i].getSum(); // 동적으로 sum 삽입
}

arr.sort(function(obj1, obj2) {
    return obj2.sum - obj1.sum;
});

console.log(' 이름   국어  영어  수학  합계');

for(let i = 0 ; i < arr.length ; ++i) {
    console.log(arr[i].name, ' ', arr[i].kor, ' ', arr[i].eng, '  ', arr[i].mat, ' ', arr[i].sum);
}

Ex08 실행결과

  • Ex09
// Ex09

// Ex08은 내껀데 이건 강사님 로직(이해하기)
function makeObj(name, kor, eng) {
    return {    // 객체 리턴
        name : name,
        kor : kor,
        eng : eng,
        sum : function() {
            return this.kor + this.eng;
        }, 
        output : function() {
            console.log(name, this.kor, this.eng, this.sum());
        },
    }
}

const arr = [];
arr.push(makeObj('강아지', 40, 30));
arr.push(makeObj('고양이', 50, 60));
arr.push(makeObj('거북이', 10, 20));

for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].output();
}
console.log('------------------');

arr.sort(function(obj1, obj2) {
    return obj1.sum() - obj2.sum();
});

for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].output();
}

Ex09 실행결과

  • Ex10
// Ex10
// 새로운 문법(생성자 함수) Ex09를 생성자 함수 이용하여 작성

// 이 함수는 생성자 함수다.
// Ex09의 예제 보다는 생성자 함수를 더 많이 사용한다.
// 생성자 함수에 대해 이해하고 알고 있기
// Ex09는 객체를 생성해서 리턴을 했고 Ex10은 new를 통해 바로 객체를 생성해 줬다는 차이에서 이 로직이 조금 더 편함
function ff(name, kor, eng) { 
    this.name = name;     // this.n은 어디 있는게 아니라 지금 만들어지는 것이다.
    this.kor = kor;
    this.eng = eng;
    this.sum = function() {
        return this.kor + this.eng;
    }
    this.output = function() {
        console.log(this.name, this.kor, this.eng, this.sum());
    }
}

/* const obj8 = new ff('고양이', 30, 20);   // 위 생성자 함수 사용법
console.log(obj8);  // 출력해 보면 알겠지만 ff인 객체가 되는 것이다. */

const arr = [];
arr.push(new ff('강아지', 40, 30));
arr.push(new ff('고양이', 50, 60));
arr.push(new ff('거북이', 10, 20));

for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].output();
}
console.log('------------------');

arr.sort(function(obj1, obj2) {
    return obj1.sum() - obj2.sum();
});

for(let i = 0 ; i < arr.length ; ++i) {
    arr[i].output();
}

Ex10 실행결과

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함