221121 Visual Studio Code(이철희쌤 3일차)

Gukbbap·2022년 11월 21일
0

보강

목록 보기
3/7
post-thumbnail

함수.html 신규 프로젝트 생성



<!DOCTYPE html>
<meta charset="UTF-8">
<script>
//자바스크립트는 함수(function)를 넘기면 80% 넘긴 것임!
//DRY원칙 (Do not Repeat Yourself)
function f_ck(){
    alert("함수가 뭐얌?");
    return; // 지정하지 않으면 생략되어 있음(종료를 알림)
    alert("요건 실행 안됨");
}
f_ck();    
</script>

함수가 만들어지기 전에 변수 생성을 해도 어플리케이션은 실행이 된다.

<!DOCTYPE html>
<meta charset="UTF-8">
<script>
//자바스크립트는 함수(function)를 넘기면 80% 넘긴 것임!
//DRY원칙 (Do not Repeat Yourself)
//100% 인터프리터 방식이 아님, 선언된건 위로 올려줌 (hoisting 호이스팅!) 사용자 몰래 최적화 작업을 진행함 
f_ck();   //←함수가 만들어지기 전에 변수 생성을 해도 어플리케이션은 실행이 된다.
function f_ck(){
    alert("함수가 뭐얌?");
    return; // 지정하지 않으면 생략되어 있음(종료를 알림)
    alert("요건 실행 안됨");
}
</script>
var aaa = 1+5+8+9;
var f_ck=function(){     // 표현식(Expression,실행문)이라 부름
    alert("함수가 뭐얌?");
    return; // 지정하지 않으면 생략되어 있음(종료를 알림)
    alert("요건 실행 안됨");
}
f_ck();

'return'은 뭐든지 할 수 있다.

// return은 뭐든지 할 수 있음!

function calculator(op){
    if(op == "+"){
        return function(p1,p2){
            return p1+p2;
        }
    }
    if(op == "-"){
        return function(p1,p2){
            return p1-p2;
        }
    }
    if(op == "*"){
        return function(p1,p2){
            return p1*p2;
        }
    }
    if(op == "/"){
        return function(p1,p2){
            return p1/p2;
        }
    }
}

alert(calculator("+")(3,4));

("+") 안에 계산식을 - * / 로 바꾸면 alert 출력값도 같이 변경된다.
산술연산 함수이기 때문에 함수가 하나의 함수를 리턴 할 수 있게 됨


즉각 실행 함수

즉각실행함수는 일반적인 소스에선 잘 안보이지만, 라이브러리 소스에는 1번 이상 등장,
핵심코드를 집약시키거나, 프로그램에서 딱 한번만 실행되어야 하는 코드가 있을 경우,
메모리를 절약하기 위해서 사용
→ 핵심코드를 메모리에 저장시키기 위해서 1번 이상 등장하게 되는 것이다.


//즉각실행함수
function(){
    
}

function 바깥에 (function(){})  형식으로 붙이면 익명으로 가리게 되고 

//즉각실행함수, 바로 실행되기 때문
(function(p_arg){
    alert("달샤벳" + p_arg);
})("수빈짱")

바깥에 () 를 붙이게 되면 즉각 실행되어진다.

이런식으로 출력됨
이를 잘난체 하는 외쿡엉아들이 사용하게 되면

+function(p_arg){
    alert("달샤벳" + p_arg);
}("유화짱")

괄호 대신에 + 를 붙여도 익명함수로 사용 할 수도 있고 익명성 함수를 유지 할 수 있게 된다.

-function(p_arg){
    alert("달샤벳" + p_arg);
}("유화짱")
!function(p_arg){
    alert("달샤벳" + p_arg);
}("유화짱")

이렇게 붙여도 사용 가능하지만

*function(p_arg){
    alert("달샤벳" + p_arg);
}("유화짱")

이렇게는 사용 할 수 없다

  • 는 제너레이터로 사용하기로 정해져 있기 때문
    그래서 통상적으로 +, -, ! 를 사용한다.

위의 표현식과 함께 자주 쓰이는 즉각실행함수 표현

함수1.html 최종


<!DOCTYPE html>
<meta charset="UTF-8">
<script>
//자바스크립트는 함수(function)를 넘기면 80% 넘긴 것임!
//DRY원칙 (Do not Repeat Yourself)
// 100% 인터프리터 방식이 아님, 선언된 건 위로 올려줌(hoisting 호이스팅!)
// return은 뭐든지 할 수 있음!

//즉각실행함수, 바로 실행되기 때문
//즉각실행함수는 일반적인 소스에선 잘 안보이지만, 라이브러리 소스에는
//1번 이상 등장, 핵심코드를 집약시키거나, 프로그램에서 딱 한번만 
//실행되어야 하는 코드가 있을 경우, 메모리를 절약하기 위해서 사용
/*
(function(p_arg){
    alert("달샤벳" + p_arg);
})("수빈짱")
*/

!function(p_arg){    // 위의 표현식과 함께 자주 쓰이는 즉각실행함수 표현
    alert("달샤벳" + p_arg);
}("유화짱")


/*
function calculator(op){
    if(op == "+"){
        return function(p1,p2){
            return p1+p2;
        }
    }
    if(op == "-"){
        return function(p1,p2){
            return p1-p2;
        }
    }
    if(op == "*"){
        return function(p1,p2){
            return p1*p2;
        }
    }
    if(op == "/"){
        return function(p1,p2){
            return p1/p2;
        }
    }
}

alert(calculator("*")(3,4));
*/
/* 
function f_ck(){
    alert("함수가 뭐얌?");
    return; // 지정하지 않으면 생략되어 있음(종료를 알림)
    alert("요건 실행 안됨");
}
*/
/*
var aaa = 1+5+8+9;
var f_ck=function(){     // 표현식(Expression,실행문)이라 부름
    alert("함수가 뭐얌?");
    return; // 지정하지 않으면 생략되어 있음(종료를 알림)
    alert("요건 실행 안됨");
}
f_ck();
*/  
</script>

함수2.html 신규 프로젝트 생성

자바스크립트 function 키워드는 class의 의미로도 사용할 수 있음!(엄청중요)

function ArrayList(){
    this["name"] = "이원걸";
    return this; // class의 의미로 사용할 때는 요거이 맨 끝에 생략되어 있음
}

이를 클래스 키워드로 사용하게 되면

var aaa = new ArrayList();
var bbb = new ArrayList();

console.log(aaa);
console.log(bbb);

이런식으로 사용 할 수 있음
이는 function을 class key로 사용하는 것임

class는 사용자 정의 data type이다.
-> 내가 필요한 데이터 타입을 새로 정의 하는 것
원시변수 이상을 사용 할 수 있기 때문에다.
원시 변수 → ' + , - , * , / ' 인데 이것으로는 내가 원하는 문장을 모두 구사 할 수 없기 때문.

function ArrayList(p_name){
    this["name"] = p_name;
    this.print = function(){  //  메소드 선언!
       document.write("<h1>" + this.name + "</h1>");
    }
    return this; // class의 의미로 사용할 때는 요거이 맨 끝에 생략되어 있음
}

var aaa = new ArrayList("유영");
aaa.print();
var bbb = new ArrayList("졸리");
bbb.print();

console.log(aaa);
console.log(bbb);

↓ 출력 화면



/*
function ArrayList(p_name){
    this["name"] = p_name;
    this.print = function(){  //  메소드 선언!
       document.write("<h1>" + this.name + "</h1>");
    }
    return this; // class의 의미로 사용할 때는 요거이 맨 끝에 생략되어 있음
}

var aaa = new ArrayList("유영");
aaa.print();
var bbb = new ArrayList("졸리");
bbb.print();

console.log(aaa);
console.log(bbb);
*/

이렇게 출력하면 출력은 잘 되지만 메모리가 아깝기 때문에

function ArrayList(){
    this.length = 0;  // 요기에 메소드를 추가하진 않음()
}
ArrayList.prototype.add = function(p_arg){
  
}

명시적으로 메소드는 밖에 선언(prototype이란 객체(별도공간)에 붙여 선언)



아래와 같은 방법으로 사용 할 수 있음
function ArrayList(){
    this.length = 0;  // 요기에 메소드를 추가하진 않음()
}
//명시적으로  메소드는 밖에 선언(prototype이란 객체(별도공간)에 붙여 선언)
ArrayList.prototype.add = function(p_arg){
    this[this.length] = p_arg;
    this.length++;
} 

var test = new ArrayList();
test.add(1);
test.add("찬솔");
test.add("용택");

console.log(test);

function ArrayList(){
    this.length = 0;  // 요기에 메소드를 추가하진 않음()
}
//명시적으로  메소드는 밖에 선언(prototype이란 객체(별도공간)에 붙여 선언)
ArrayList.prototype.add = function(p_arg){
    this[this.length] = p_arg;
    this.length++;
} 
ArrayList.prototype.get = function(p_index){
    return this[p_index];
}

var test = new ArrayList();
test.add(1);
test.add("찬솔");
test.add("용택");

console.log(test.get(1));


ps) javascript에서 속성을 지울때는 delete를 사용한다.


ArrayList.prototype.add = function(p_arg){
    this[this.length] = p_arg;
    this.length++;
} 
ArrayList.prototype.get = function(p_index){
    return this[p_index];
}
ArrayList.prototype.clear = function(){
    for(var i=0; i<this.length; i++){
        delete this[i];
    }
}


var test = new ArrayList();
test.add(1);
test.add("찬솔");
test.add("용택");

console.log(test.clear());
console.log(test);

속성이 모두 사라진 것을 확인 할 수 있다.

undefined가 출력 되는 이유는 속성을 초기화 시켰기 때문이다.

ArrayList.prototype.add = function(p_arg){
    this[this.length] = p_arg;
    this.length++;
} 
ArrayList.prototype.get = function(p_index){
    return this[p_index];
}
ArrayList.prototype.clear = function(){
    for(var i=0; i<this.length; i++){
        delete this[i];
    }
    this.length = 0;   // 다 지웠으니까 갯수는 0으로 세팅하는 게 맞음!
    return;
}


var test = new ArrayList();
test.add(1);
test.add("찬솔");
test.add("용택");

test.clear();
console.log(test);

이렇게 처리 해 줘서

으로 나와야 한다.


확인사살문제

ArrayList.prototype.remove = function(p_index){
// 코드를 작성하시옹, remove(1) 하면 index번호 1에 해당하는 내용 삭제
// 0:1, 1:용택, length:2 가 나와야 함

풀이


ArrayList.prototype.remove = function(p_index){
    for(var i=p_index; i<this.length-1; i++){
        this[p_index] = this[p_index+1];  // 1개씩 앞으로 땡기깅
    }
    delete this[this.length-1];  //마지막꺼 지우깅
    this.length--;

profile
Johannes

0개의 댓글