728x90

JQuery를 이해하기 위해 직접 만들어보는 Query 

 

window.kQuery=function(arg){//arg = selector, function, dom Node

if(typeof arg == 'string'){

//css selector

let elementNodeList =document.querySelectorAll(arg);

if(!elementNodeList)elementNodeList=[];//list가 없으면 []초기화

 

let jqueryWrapperObject = {

'elementNodeList':elementNodeList,

'css':function(propertyName,propertyValue){

for(let i=0; i<this.elementNodeList.length;i++){

this.elementNodeList[i].style.cssText=`${propertyName}:${propertyValue}`;

}

return this;

},

'text':function(textArg){

if(!textArg){//falsy, getter

let returnText="";

for(let i=0; i<this.elementNodeList.length;i++){

returnText+=this.elementNodeList[i].innerHTML;

}

return returnText;

}else{//setter

for(let i =0; i<this.elementNodeList.length;i++){

this.elementNodeList[i].innerHTML=textArg;

}

return this;

}

}

};

return jqueryWrapperObject;

}

if(typeof arg == 'function'){

/*

인자로 대입된 함수를 DOM 트리 생성직후에 호출되도록

window.onload 이벤트 프로퍼티에 등록

*/

window.addEventListener('load',arg);

}

if(typeof arg == 'object'){

//dom node

}

if(typeof arg == 'undefined'){

//arg가 없을때

}

}

/****Jquery[$] global function */

kQuery.each=function(array, functionArg){

for(let i=0;i<array.length;i++){

functionArg(i,array[i]);

}

};

window.$=window.kQuery;

window에 kQuery 라는 펑션 프로퍼티를 등록한다. 

이 kQuery 펑션은 파라메터를 받을 수 있다. 

window.kQuery=function(arg){

}

파라메터를 받은 후 파라메터의 타입을 구분해 타입에 따라 처리하는게 달라진다.

if(typeof arg == 'string'){

//css selector

let elementNodeList =document.querySelectorAll(arg);

if(!elementNodeList)elementNodeList=[];//list가 없으면 []초기화

 

let jqueryWrapperObject = {

'elementNodeList':elementNodeList,

'css':function(propertyName,propertyValue){

for(let i=0; i<this.elementNodeList.length;i++){

this.elementNodeList[i].style.cssText=`${propertyName}:${propertyValue}`;

}

return this;

},

'text':function(textArg){

if(!textArg){//falsy, getter

let returnText="";

for(let i=0; i<this.elementNodeList.length;i++){

returnText+=this.elementNodeList[i].innerHTML;

}

return returnText;

}else{//setter

for(let i =0; i<this.elementNodeList.length;i++){

this.elementNodeList[i].innerHTML=textArg;

}

return this;

}

}

};

return jqueryWrapperObject;

}

css selector에 들어갈 선택자 String이 입력되면 

선택된 노드들을 WrapperNode로 만들고 

다양한 함수를 사용할 수 있게 WrapperNode에 함수들을 붙여준다. 

위 예제에서는 text()를 get하거나 set하는 text()함수와 css를 변경해주는 css()함수를 만들었고

css()함수는 wrapper 객체의 css를 변경해준뒤 다시 반환해준다.

text()함수는 인자가 없는 경우 객체의 text를 반환하고 인자가 있는 경우 객체의 text를 인자의 string으로 바꾼뒤 반환해준다. 

 

if(typeof arg == 'function'){

/*

인자로 대입된 함수를 DOM 트리 생성직후에 호출되도록

window.onload 이벤트 프로퍼티에 등록

*/

window.addEventListener('load',arg);

}

만약 함수가 kQuery에 인자로 들어온다면 인자로 대입된 함수를 onload 이벤트 프로퍼티에 등록한다.

 

kQuery.each=function(array, functionArg){

for(let i=0;i<array.length;i++){

functionArg(i,array[i]);

}

};

kQuery가 가지는 함수를 정의해준다. 위 예제는 반복문을 정의하였다. 

kQuery.each(array,function(){});

사용할 때는 kQuery에 바로 each 함수를 호출하여 반복할 array와 함수를 인자로 대입해준다. 

 

window.$=window.kQuery;

JQuery는 $로도 사용하는데 

window.$에 kQuery를 등록하면 kQuery도 $로 사용할 수 있다. 

'Javascript' 카테고리의 다른 글

JQuery effect  (0) 2023.09.22
JQuery 입문  (1) 2023.09.22
Javascript defer  (0) 2023.09.21
CSS 선택자를 이용한 HTML DOM 객체 Handling  (0) 2023.09.18
Javascript intermediate  (0) 2023.09.18
728x90

브라우저가 HTML을 읽다가 <script> 태그를 만나면 HTML 파싱을 멈추고 <script>를 먼저 실행합니다. 

이때문에 DOM 객체 생성이 중단되고 사용자는 HTML 이 다 파싱될 때까지 UI를 사용하지 못하는데 

 

<script src> src 속성을 가져 파일을 다운받아오는 script태그는 다운로드가 오래 걸리면 다운로드가 완료될때까지 

파싱이 지연되게 됩니다.

 

이를 해결하기 위해 <script> 태그를 body 끝부분에 위치시키거나

defer 속성을 사용합니다. 

 

script src 는 태그 순서대로 실행되기로 되어있고 

다운로드가 먼저끝나더라도 실행은 태그의 위치 순서에 따른다.

 

defer 속성을 사용하면 script를 백그라운드에서 병렬적으로 다운로드 받고 HTML을 멈추지 않고 계속 파싱합니다.

 

<script defer src="small.js">

 

'Javascript' 카테고리의 다른 글

JQuery 입문  (1) 2023.09.22
JQuery 이해하기  (0) 2023.09.22
CSS 선택자를 이용한 HTML DOM 객체 Handling  (0) 2023.09.18
Javascript intermediate  (0) 2023.09.18
Javascript Event  (0) 2023.09.17
728x90

선택자 

1. querySelector('key')

document.querySelector('div');

 검색된 결과들 중 첫번째 결과만 반환

2. querySelectorAll('key')

document.querySelectorAll('div');

 검색된 모든 결과를 반환 (리스트로 반환)

 

키값 ==style(css)에서와 동일하게 적용

 

#id

.class

tagname

<style type="text/css">
    <!--#idSelector--.classSelector----tagSelector-->
    #title{
        color:maroon;
    }
    .contents{
        color:pink;
    }
    h2{
        color: gold;
    }
   
</style>
document.querySelector('#title').style.color='maroon'; // # : title이란 id를 가진 노드
document.querySelector('.contents').style.color='pink'; // . : contents란 class를 가진 노드 검색
document.querySelectorAll('h2')[1].style.color='tomato';// tagName : tag로 검색

 

A, B  :  A  또는 B

AB : A 그리고 B 

div,span{
    width: 100px;
}
document.querySelectorAll('span,div');

> div태그 또는 span 태그 

 

#content,div{
    border:1px solid red;
}
document.querySelectorAll('#content,div');

> id가 content인 노드 또는 div태그

 

div.myClass{
    background-color:pink;
}
querySelectorAll('div.myClass');

>div태그 중 class가 myClass인 노드 

 

 

직계자식 ( > ) : 객체의 바로 한 단계 하위의 객체들 

자손 (   ): 객체의 하위 모든 객체들

 

body > div {
    border: 3px dotted orange;
}
document.querySelectorAll('body > div');

> body 의 직계자식 중 div 인 노드들

 

body  div {
    background-color: yellow;
}
document.querySelectorAll('body div');

> body의 자손 중 모든 div 노드들

'Javascript' 카테고리의 다른 글

JQuery 이해하기  (0) 2023.09.22
Javascript defer  (0) 2023.09.21
Javascript intermediate  (0) 2023.09.18
Javascript Event  (0) 2023.09.17
Javascript Basic  (5) 2023.09.15
728x90

변수 선언 

 

전역에 선언된 var 변수는 window속성으로 생성된다. 

전역에 선언된 var 변수는 중복선언이 되어도 에러가 발생하지 않는다.  

    var a3 = 1;
    var a3 = 2;

전역에 선언된 let 변수는 window속성으로 생성되지 않는다. 

전역에 선언된 let 변수는 중복선언되면 에러가 발생한다. 

let 변수는 해당 let이 속한 블록의 범위내에서 유효하다. 

let a2 = 2;
let a2 = 'text2'; //에러발생

 

javascript에는 null 과 undefined가 있다. 

null은 말그대로 값이 없다는 뜻이고 

undefined는 값이 지정되지 않았다는 뜻으로 값이 없는지 있는지조차 모른다

 

null은 값이 없다는 것을 명시적으로 밝히기 위해 의도적으로 사용하는 것이고

undefined는 변수는 생성되었으나 변수의 값이 초기화되기 전 반환되는 값이다.

 

typeof null  ==> Object 

typeof undefined ==> undefined

 

 

Falsy & Truthy 

false로 간주되는 값과 truth로 간주되는 값 

falsy, truthy한 값은 논리형 타입으로 자동 변경되어 의도하지 않은 결과를 일으킬 수 있다. 

 

-falsy values : 0, null, undefined, '' 

let zeroNumber = 0;
let nullValue = null;
let emptyString = '';
let undefinedVar;

위 값들은 조건문과 같이 논리형을 필요로하는 곳에서 논리형으로 변경되어 반환된다. 

if(!zeroNumber){
       console.log('zeroNumber=false, !zeroNumber=true이므로 실행되는 코드');
    }

 

-truthy values : 0이 아닌 숫자, emptyStr이 아닌 문자열

let zeroNumberStr = '0';
    let boolStr = 'false';
    let spaceStr = ' ';
    let number = 213213;
    let str='이름';

String 값이 '0'이더라도 0이라는 내용과 관계없이 emptyStr이 아니므로 truthy 

 

 

 

 

Object 객체생성 

1. 생성자 함수 

let o1 = new Object();
    o1.data=1;
    o1.data2 = 2;
    o1.cm = function(){};

o1 변수에 객체를 생성하고 o1에 data 변수를 만들어 1을 초기화 해준다. 

자바에서는 객체에 필드가 있어야 값을 초기화할 수 있지만 

자바스크립트에서는 객체의 멤버필드를 동적으로 생성할 수 있기 때문에 

Object를 생성후 data, data2, cm 의 선언이 가능한 것이다.

 

이러한 방식은 같은 객체를 표현할때마다 갖는 프로퍼티가 달라질 수 있다. 

자바의 클래스와 같이 같은 객체는 같은 프로퍼티를 갖게 하기 위해서 사용할 수 있는 방법

 

-학생 객체를 생성해서 반환해주는 function을 작성

function createStudent(id,name,kor,eng,math){
        let studentObject={
        id:id,
        name:name,
        kor:kor,
        eng:eng,
        math:math,
        tot:0,
        avg:0.0,
        calculateTot:function(){this.tot=this.kor+this.eng+this.math},
        calculateAvg:function(){this.avg=this.tot/3},
        toString:function(){
            document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.avg+" "+this.tot+" ");
        }
    };
    return studentObject;
    }

정해진 인자를 받고 정해진 프로퍼티를 갖는 student 객체를 생성해준다. 

 

-Student 생성자 함수 작성

function Student(id,name,kor,eng,math){
        this.id=id;
        this.name=name;
        this.kor=kor;
        this.eng=eng;
        this.math=math;
        this.tot=0;
        this.avg=0.0;
        this.calculateTot=function(){
            this.tot=this.kor+this.eng+this.math;
        };
        this.calculateAvg=function(){
            this.avg=this.tot/3;
        };
        this.toString=function(){
            document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.math+" "+this.tot+" "+this.avg);
        };
    }
Student('xxx','xman',12,23,20);//student는 window에
Student('yyy','yman',14,49,39);//student는 window에 y가x를 덮어버림

생성자 함수를 사용할 때 이런식으로 생성하면 생성된 Student는

window에 등록되고 window에 다시 등록하면 기존의 Student를 덮어버린다. 

let studentObject1 = new Student('xxx','xman',12,23,20);
let studentObject2 = new Student('yyy','yman',14,49,39);

생성자함수의 생성시 new 예약어를 붙여준다. 

new 예약어는 Object객체를 생성해주고 Object객체에 속성을 추가한뒤 객체를 반환해준다. 

이러한 방식도 여전히 각 객체마다 동일한 함수를 가져야한다는 단점이 있다. 

 

-Prototype을 사용한 방식

function Student(id, name, kor, eng, math) {
   
    this.id = id;
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.tot = 0;
    this.avg = 0.0;

}
Student.prototype = {
    calculateTot: function() {
        this.tot = this.kor + this.eng + this.math;
    },
    calculateAvg: function() {
        this.avg = this.tot / 3;
    },
    toString: function() {
        return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
    }

}
 
new Student('xxx', '김', 23, 56, 78).calculateTot();

Student.prototype에 function들을 정의해준다. 

function을 사용할 땐 student 객체에서 바로 .calculateTot()로 접근해주면 된다.

 

-class를 이용한 방식

class Student{
   
    constructor(id,name,kor,eng,math){
        this.id = id;
        this.name = name;
        this.kor = kor;
        this.eng = eng;
        this.math = math;
        this.tot = 0;
        this.avg = 0.0;
    }
    calculateTot(){
        this.tot = this.kor + this.eng + this.math;
    }
    calculateAvg(){
        this.avg = this.tot / 3;
    }
    toString(){
        return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
    }
   
}

사용법은 이전과 동일하다 

 

-자바의 객체지향을 흉내낸 패키지 개념의 생성자

com={};


com.Student= function(id, name, kor, eng, math) {

    this.id = id;
    this.name = name;
    this.kor = kor;
    this.eng = eng;
    this.math = math;
    this.tot = 0;
    this.avg = 0.0;


}

/************prototype[JSON][case 2]***********/
com.Student.prototype = {
    calculateTot: function() {
        this.tot = this.kor + this.eng + this.math;
    },
    calculateAvg: function() {
        this.avg = this.tot / 3;
    },
    toString: function() {
        return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
    }

}

com이라는 객체를 생성하고 

com 객체안에 Student 생성자를 만든다. 

new com.Student('j','j',1,2,3)

생성할때도 com 객체를 붙여주어야 하고 

student 객체에 접근할 때도 com을 통해 접근해야한다.

 

 

2. JSON 방식 

let o2 = {
        data:1,
        data2:2,
        cm: function(){}
    }; //json

JSON표기법으로 객체를 생성할 수 있다 

{

    변수 : 값,

    함수명 : 함수

}

 

Array 배열

1.Array객체 생성

let array1 = new Array();
    array1.a = 1;

Array() 객체를 생성하면 Array 객체의 function들을 사용할 수 있다.

2.JSON 방식 

let scoreArray=[34,56,78,90,100];

Object객체는 {...}로 

Array 객체는 [...]로 표기한다.

 

객체를 담은 배열은  [ {...}, {...}, ...];

let studentArr = [
    {
        no:1,
        name:"KIM",
        score:34
    },
    {
        no:2,
        name:"LEE",
        score:56
    }
    ];

 

객체를 상수로 생성하는 경우

const studentObject1={
        id:'xxx',
        name:'sim',
        kor:47,
        eng:89,
        math:99,
        tot:0,
        avg:0.0,
        calculateTot:function(){this.tot=this.kor+this.eng+this.math},
        calculateAvg:function(){this.avg=this.tot/3},
        toString:function(){
            document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.avg+" "+this.tot+" ");
        }
    };

const는 상수이기 때문에 변경이 불가능하다.

여기서 상수는 studentObject1의 참조변수이지 studentObject1의 프로퍼티가 아니다. 

즉 id, name, kor, ...등은 얼마든지 변경 가능하다.

studentObject1=studentObject2; 실행결과

studentObject1은 상수이기 때문에 studentObject2로 변경이 불가능하다. 

studentObject1.id='zzz'; 실행결과

반면, studentObject1.id는 상수가 아니기 때문에 변경이 가능하다.

 

 

함수 

자바스크립트에선 함수를 인자로 받고, 변수에 대입하거나 반환하는 것이 가능하다.

function func4(functionArg,funcArg){
       let funcLet =  functionArg();
       return funcArg();
    }
 
func4(
            function(){
                ...
            },
            function(){
                ...
            }
        );

 

 

함수 선언 방법

 

이름이 존재하는 선언적 함수 선언

1. function name(param){...code...}

 

익명함수 선언 

2. function (param){...code...}

function (msg){
           ...
        };

3. (param) => {...code...}

(msg)=>{
           ...
        }

4. param => {...code...}

msg=>{
           ...
            }

익명함수의 선언과 실행

(function(){
        document.write('익명함수가 실행<br>');
    })();

(function(){...}) (); 

익명함수를 선언하고 바로 (); 실행할 수 있다. 

 

파라메터가 존재하지 않을 수 있고, 다수의 파라메터를 받을 수도 있다. 

파라메터는 변수나 함수를 받을 수 있다. 표준자바스크립트 함수 (alert, confirm...)도 파라메터로 쓸 수 있다.

var alertVar = window.alert;
    var confirmVar = confirm;

 

Closure 클로져

내부함수가 참조하는 외부함의 지역변수가 외부함수에 의해 내부함수가 반환된 이후에도 환경이 유지되는 것

 

function outer_function2(){
            let outer2_var="outer2 로컬변수데이터";
            return function(){
                let inner2_var="inner2 로컬변수데이터";
                document.write("익명 inner_function2--> outer2_var:"+outer2_var+"<br>");
                document.write("익명 inner_function2--> inner2_var:"+inner2_var+"<br>");
            };
    }
 
let return_inner_function2=outer_function2();
        return_inner_function2();
실행결과

//실행결과

//outer_function2() 실행이 끝나고 inner_function2를 반환받아서 실행하면 outer_function2의 변수와 inner_function2의 변수를 모두 사용할 수 있다.

 

 

 

 

DOM객체 찾기

-document.getElementById();

돔트리 전체에서 Id로 검색

 

-pE.getElementById();

pE노드의 하위 노드중에서 Id로 검색

 

 

DOM객체의 동적 생성

document.createElement("tagName");

let newDivE =document.createElement("div");
    newDivE.setAttribute("id","newDiv"+count);
    newDivE.setAttribute("style",`border: 1px dotted gold`);

태그 네임을 받아 원하는 객체를 생성할 수 있다. 

생성된 객체에 setAttribute("attribute","value"); function으로 객체에 속성을 설정할 수 있다.

 

document.createTextNode(textMsgStr);

   let newTextNode=document.createTextNode('textMessage');

텍스트 노드는 html의 텍스트 컨텐츠이다. 

 

parentElement.appendChild(childElement);

 let parentDivE = document.getElementById("parent");
 parentDivE.appendChild(newDivE);
newDivE.appendChild(newTextNode);

P.appendChild(C); 는 P부모객체의 마지막 자식 노드에 C자식 객체를 붙여준다.

순서에 유의해야한다. 

.insertBefore(추가할 노드, 기준노드) 메서드를 사용하면 위치를 어느정도 능동적으로 조정할 수 있다.

기준노드의 앞에 추가할 노드를 추가한다.

 

parentElement.removeChild(childElement);

parentDivE.removeChild(removeDivE);

P객체의 자식객체를 삭제한다.

 

 

'Javascript' 카테고리의 다른 글

JQuery 이해하기  (0) 2023.09.22
Javascript defer  (0) 2023.09.21
CSS 선택자를 이용한 HTML DOM 객체 Handling  (0) 2023.09.18
Javascript Event  (0) 2023.09.17
Javascript Basic  (5) 2023.09.15

+ Recent posts