728x90
반응형
728x90
반응형

함수예고(함수=수납상자)

nightDayHandler(){} 함수를 정의함으로써 긴 코드의 길이를 줄일 수 있습니다.


함수

BASIC

코드가 반복되어야 하는 경우 반복문을 처리해 사용하면 되지만 연속적으로 반복해야 하는 경우가 아니라면 반복문을 사용할 수 없게 됩니다. 이때 함수를 사용해 해결할 수 있습니다.

<h1>Function</h1>

 <h2>Basic</h2>

 <ul>

      <script>

        function two(){

          document.write('<li>2-1</li>');

          document.write('<li>2-2</li>');

        }

        document.write('<li>1</li>');

        two();

        document.write('<li>3</li>');

        two();

      </script>

</ul>

Parameter & Argument 함수 입력부분이 파라미터


<h2>Parameter & Argument</h2>

    <script>

      function onePlusOne(){

        document.write(1+1+'<br>');

      }

      onePlusOne();

      function sum(left, right){  //left, right를 매개변수 parameter

        document.write(left+right+'<br>');

      }

      sum(2,3); //5 2,3을 인자 argument라 합니다.

      sum(3,4); // 7

    </script>

Return 함수 출력부분은 리턴

<h2>Return</h2>

    <script>

      function sum2(left, right){

        return left+right;

      }

      document.write(sum2(2,3)+'<br>');

      document.write('<div style="color:red">'+sum2(2,3)+'</div>');

      document.write('<div style="font-size:3rem;">'+sum2(2,3)+'</div>');

    </script>

 

함수의 활용

함수를 호출할 때 인자로 this를 주면 nightDayHandler(self)함수 내에 포함되어 있는 input태그 자체가 인자로 함수에 전달됩니다. 함수는 self라는 파라미터로 인자로 전달받게 되고 self라는 값은 함수를 호출한 input태그가 됩니다. 따라서 클릭을 함으로 value night day로 변경이 됩니다. 

WEB

  1. HTML
  2. CSS
  3. JavaScript

WEB

  1. HTML
  2. CSS
  3. JavaScript

객체예고

객체는 변수와 함수를 정리정돈하기 위한 도구

function LinksSetColor(color){ //a태그 전체의 색을 변경

    var alist = document.querySelectorAll('a');

    var i = 0;

    while(i < alist.length){

      alist[i].style.color = color;

      i = i + 1;

    }

  }

  function BodySetColor(color){ //바디태그의 글씨색을 변경

    document.querySelector('body').style.color = color;

  }

  function BodySetBackgroundColor(color){ //바디태그의 배경색을 변경

    document.querySelector('body').style.backgroundColor = color;

  }

  function nightDayHandler(self){

    var target = document.querySelector('body');

    if(self.value === 'night'){

      Body.setBackgroundColor('black');

      Body.setColor('white');

      self.value = 'day';

      Links.setColor('powderblue');

    } else {

      Body.setBackgroundColor('white');

      Body.setColor('black');

      self.value = 'night';

      Links.setColor('blue');

    }

}

객체를 만들지 않았기 때문에 함수는 동작하지 않습니다.

 

객체(object)

객체의 쓰기와 읽기

<h1>Object</h1>

    <h2>Create</h2>

    <script>

      var coworkers = {

        "programmer":"egoing",

        "designer":"leezche"

      };

      document.write("programmer : "+coworkers.programmer+"<br>");

      document.write("designer : "+coworkers.designer+"<br>");

      coworkers.bookkeeper = "duru";

      document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");

      coworkers["data scientist"] = "taeho";

      document.write("data scientist : "+coworkers["data scientist"]+"<br>");

    </script>

객체와 반복문

<h2>Iterate</h2>

<script>

    for(var key in coworkers) {

      document.write(key+' : '+coworkers[key]+'<br>');

    }

</script>

프로퍼티와 메소드(자바스크립트에서 객체는 함수도 담을 수 있습니다.)

<h2>Property & Method</h2>

    <script>

      coworkers.showAll = function(){

        for(var key in this) {

          document.write(key+' : '+this[key]+'<br>');

        }

      }

      coworkers.showAll();

    </script>

showAll함수 안에서 소속된 객체를 가리키는 약속된 기호를 this 

객체의 소속된 변수에 값으로 함수를 만들 수 있습니다.

객체의 소속된 함수를 메소드, 객체의 소속된 변수를 프로퍼티 


체 활용

WEB

  1. HTML
  2. CSS
  3. JavaScript

JavaScript

WEB

  1. HTML
  2. CSS
  3. JavaScript

JavaScript

파일로 쪼개서 정리 정돈하기

수정하고자 하는 코드를 변경하면 코드가 실행되지만 여러 개의 코드가 있는 경우 각각의 코드를 변경하는 것이 쉬운 작업은 아닙니다.

.js파일로 따로 공통된 코드를 정의하여 <script src=”colors.js”></script> 구현하면 쉽게 처리할 수 있습니다. js파일 내에는 <script>태그가 들어가면 안됩니다.

.js파일에 따로 코드를 분류를 하게 되면 유지보수가 수월해집니다.

코드의 명확성이 높아지고 가독성이 높아지게 됩니다. 여러 개의 파일로 쪼개는 것이 파일을 정리정돈하는 방법입니다.

*웹 페이지에 다운로드된 파일은 컴퓨터에 저장되어 다음 접속 시에는 저장된 파일을 읽어 네트워크를 통하지 않게 합니다. 서버입장에서 비용을 절감하는 효과를 얻습니다. 사용자 입장에서 네트워크 트래픽을 절감하고 빠르게 웹 페이지를 볼 수 있는 효과가 있습니다.

 

라이브러리와 프레임워크(서로 협력하는 모델)

라이브러리는 재사용하기 쉽도록 정리정돈 되어있는 소프트웨어. (만들어진 것을 쓰는 것)

프레임워크는 만들고자 하는 것이 있을 때 무엇이냐에 따라 게임, , 채팅 등

만들고자 하는 부분에 공통부분을 프레임워크 개성에 따라 다른 부분만 수정할 수 있도록 하는 것.

라이브러리(jQuery)

CDN(Content Delivery Network): 직접 라이브러리를 다운로드 받아 프로젝트 포함시켜 업로드하고 서비스하려면 비용이 듭니다. 많은 라이브러리가 CDN을 통해 자신들의 서버에 파일을 보관해 우리는 그것을 <script src=”.js”>를 통해 가져가는 방식으로 사용료까지 내줌으로 편한 작업입니다.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

var Links = {

   setColor:function(color){

$('a').css('color', color);

   }

 }


UI(User Interface) vs API(Application Programming Interface)

UI : 사용자가 조작 장치를 이용해 웹 애플리케이션을 사용하고 있는 것

 API : 경고창이 실행되는 것은 웹 브라우저를 만드는 사람이 경고창을 미리 만든 것, 조작 장치 alert API라고 합니다.

사용자는 UI, 프로그래머는 UI+API를 모두 사용, 자신만의 응용프로그램을 만들 수 있다.

 

수업을 마치며

Cookie 개인화된 서비스를 제공, offline web application 인터넷이 끊겨도 동작하고자 하는 앱

webRTC 화상통신, webGL 3차원 그래픽, webVR 가상현실


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

Element 객체

Element 객체는 엘리먼트를 추상화한 객체

DOM은 마크업언어를 제어하기 위한 표준

 


 -식별자 API

<script>

console.log(document.getElementById('active').tagName)// LI
 var active = document.getElementById('active');
console.log(active.id); // active
var active = document.getElementById('active');
// class 값을 변경할 때는 프로퍼티의 이름으로 className을 사용
active.className = "important current";
console.log(active.className); // important current
active.className += " readed" // 클래스를 추가할 때는 아래와 같이 문자열의 더한다.
var active = document.getElementById(‘active’);
for(var i=0; i<active.classList.length; i++){
        console.log(i, active.classList[i]);
}
active.classList.add('marked'); // 추가
active.classList.remove('important'); // 제거
active.classList.toggle('current'); // 토글
</script>


 -조회 API

  <script>

    var list = document.getElementsByClassName('marked');

    console.group('document');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent); // html, dom, bom

    }

    console.groupEnd();

    

    console.group('active');

    var active = document.getElementById('active');    

    var list = active.getElementsByClassName('marked');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent); // dom, bom

    }

    console.groupEnd();

</script>

  

 -속성 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script>

var t = document.getElementById('target');

console.log(t.setAttribute(‘href’, ‘http://opentutorials.org/course/1’);

console.log(t.getAttribute('href')); //http://opentutorials.org

t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.

t.removeAttribute('title'); // title 속성을 제거한다.

console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.

</script>

속성과 프로퍼티

<p id="target">

    Hello world

</p>

<script>

    var target = document.getElementById('target');  

    target.setAttribute('class', 'important');  // attribute 방식

    target.className = 'important'; //// property 방식

</script>

속성과 프로퍼티 둘의 차이점

<a id="target" href="./demo1.html">ot</a>

<script>

//현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때

var target = document.getElementById('target');

console.log('target.href', target.href); // http://localhost/webjs/Element/attribute_api/demo1.html

console.log('target.getAttribute("href")', target.getAttribute("href")); // ./demo1.html

</script>

 -jQuery 속성 제어 API

<a id="target" href="http://opentutorials.org">opentutorials</a>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

var t = $('#target');

console.log(t.attr('href')); //http://opentutorials.org

t.attr('title', 'opentutorials.org'); // title 속성의 값을 설정한다.

t.removeAttr('title'); // title 속성을 제거한다.

</script>

jquery에서 attribute property

<a id="t1" href="./demo.html">opentutorials</a>

<input id="t2" type="checkbox" checked="checked" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

// 현재 문서의 URL이 아래와 같다고 했을 때,

// http://localhost/jQuery_attribute_api/demo2.html

var t1 = $('#t1');

console.log(t1.attr('href')); // ./demo.html

console.log(t1.prop('href')); // http://localhost/jQuery_attribute_api/demo.html

 

var t2 = $('#t2');

console.log(t2.attr('checked')); // checked

console.log(t2.prop('checked')); // true

</script>

Attr attribute, prop property 방식

 -jQuery 조회 범위 제한

<ul>

    <li class="marked">html</li>

    <li>css</li>

    <li id="active">JavaScript

        <ul>

            <li>JavaScript Core</li>

            <li class="marked">DOM</li>

            <li class="marked">BOM</li>

        </ul>

    </li>

</ul>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    //$( ".marked", "#active").css( "background-color", "red" );

    //$( "#active .marked").css( "background-color", "red" );

    $( "#active").find('.marked').css( "background-color", "red" );

</script>

find를 너무 복잡하게 사용하면 코드를 유지보수하기 어렵습니다.

Node객체

시조는 최상위의 조상을 의미

node객체는 최상위 객체를 의미, 모든 객체는 node객체를 상속받음

 -Node 관계 API

 

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

var s = document.getElementById('start');

console.log(1, s.firstChild); // #text

var ul = s.firstChild.nextSibling

console.log(2, ul); // ul

console.log(3, ul.nextSibling); // #text, 다음 형제 노드

console.log(4, ul.nextSibling.nextSibling); // script

console.log(5, ul.childNodes); //text, li, text, li, text, li, text

console.log(6, ul.childNodes[1]); // li(html), 자식노드들을 유사배열에 담아서 리턴

console.log(7, ul.parentNode); // body

</script>

</body>

 -노드 종류 API

Node.nodeType // node의 타입을 의미

Node.nodeName // node의 이름 (태그명을 의미)

재귀함수 : 함수가 지가 자신을 호출하는 것

<!DOCTYPE html>

<html>

<body id="start">

<ul>

    <li><a href="./532">html</a></li>

    <li><a href="./533">css</a></li>

    <li><a href="./534">JavaScript</a>

        <ul>

            <li><a href="./535">JavaScript Core</a></li>

            <li><a href="./536">DOM</a></li>

            <li><a href="./537">BOM</a></li>

        </ul>

    </li>

</ul>

<script>

function traverse(target, callback){

    if(target.nodeType === 1){ // 1==Node.ELEMENT_NODE

        //if(target.nodeName === 'A')

        callback(target);

        var c = target.childNodes; // 자식 노드들을 유사배열에 담아서 리턴

        for(var i=0; i<c.length; i++){

            traverse(c[i], callback);      

        }  

    }

}

traverse(document.getElementById('start'), function(elem){

    console.log(elem);

});

</script>

</body>

</html>

 -노드 변경 API

   

appendChild(child) // 노드의 마지막 자식으로 주어진 엘리먼트 추가

insertBefore(newElement, referenceElement) // appendChild와 동작방법은 같으나 두번째 인자로 엘리먼트를 전달 했을 때 이것 앞에 엘리먼트가 추가

removeChild(child) // 노드 제거

replaceChild(newChild, oldChild) // 노드 바꾸기

 -jQuery 노드 변경 API

.jQuery에서 노드를 제어하는 기능은 주로 Manipulation 카테고리에 속해 있음

<div class="target">

    content1

</div>

<div class="target">

    content2

</div>

 

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('.target').before('<div>before</div>');

    $('.target').after('<div>after</div>');

    $('.target').prepend('<div>prepend</div>'); // 이전 추가

    $('.target').append('<div>append</div>'); // 이후 추가

</script>

remove는 선택된 엘리먼트를 제거하는 것이고 empty는 선택된 엘리먼트의 텍스트 노드를 제거하는 것

<div class="target" id="target1">

    target 1

</div>

<div class="target" id="target2">

    target 2

</div>

 

<input type="button" value="remove target 1" id="btn1" />

<input type="button" value="empty target 2" id="btn2" />

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<script>

    $('#btn1').click(function(){

        $('#target1').remove();

    })

    $('#btn2').click(function(){

        $('#target2').empty();

    })

</script>

교체

 

클론

이동

 -문자열 노드 제어

   innerHTML : 문자열로 자식 노드를 만들 수 있는 기능을 제공

   outerHTML : 선택한 엘리먼트를 포함해서 처리

   innerTEXT, innerTEXT : innerHtml, outerHTML과 다르게 이 API들은 값을 읽을 때는 HTML 코드를 제외한 문자열을 리턴하고, 값을 변경할 때는 HTML의 코드를 그대로 추가

   insertAdjacentHTML : 좀 더 정교하게 문자열을 이용해서 노드를 변경하고 싶을 때 사용

   

 



출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

상속(Inheritance)

객체지향에서 중요한 개념입니다. 객체라는 것은 하나의 컨테이너이고 객체는 변수, 메소드로 모아져있습니다. 객체의 특성을 물려받아 새로운 객체를 만들수 있습니다. 새로운 객체는 부모 객체와 동일한 기능을 가질 수 있습니다. 부모의 기능을 그대로 사용하거나 추가할 수 있습니다. 이것이 바로 상속의 기본적인 동작 방식입니다. 이를 통해 로직을 재활용 할 수 있습니다.

부모의 재산을 자식이 상속받듯이 오리지널 객체의 기능을 동일하게 받을 수 있습니다.

function Person(name){

    this.name = name;

    this.introduce = function(){

        return 'My name is '+this.name;

    }  

}

var p1 = new Person('egoing');

document.write(p1.introduce()+"<br />"); // My name is egoing

 

function Person(name){ //생성자를 만들어서

    this.name = name;

}

Person.prototype.name=null; //객체의 prototype이라는 프로퍼티가 있는데 .name시 이름을 준다.

Person.prototype.introduce = function(){

    return 'My name is '+this.name;

}

var p1 = new Person('egoing');

document.write(p1.introduce()+"<br />");

자바스크립트의 상속 구현에 대해 알아보겠습니다.

function Person(name){

    this.name = name;

}

Person.prototype.name=null;

Person.prototype.introduce = function(){

    return 'My name is '+this.name;

}

 

function Programmer(name){

    this.name = name;

}

Programmer.prototype = new Person(); //상속받음

 

var p1 = new Programmer('egoing'); //Programmer생성자 호출

document.write(p1.introduce()+"<br />");

 

객체가 기능을 물려받았으니 새로운 기능을 추가하는 방법에 대해 알아보겠습니다.

Programmer.prototype.coding = function(){

    return "hello world";

}

document.write(p1.coding()+"<br />"); // hello world가 출력

 

function Designer(name){

    this.name = name;

}

Designer prototype = new Person();

Designer.prototype.design = function(){

    return "beautiful!";

}

var p2 = new Designer('leezche');

document.write(p1.introduce()+"<br />");

document.write(p1.design()+"<br />"); //beautiful!을 출력

 

prototype 원형(원래 형태)

객체지향 언어와 자바스크립트를 구분하는 개념

생성자는 기본적으로 함수입니다. 함수를 호출할 때 new로 인해 단순한 함수가 아닌 생성자로 변합니다. 새로운 객체를 만들어 리턴합니다. 어떤 객체를 만들 때 객체가 가져야 하는 메소드, 데이터가 주어지길 바라기 때문에 생성자를 사용합니다.

function Ultra(){}

Ultra.prototype.ultraProp = true;

 

function Super(){}

Super.prototype = new Ultra();

 

function Sub(){}

Sub.prototype = new Super();

Sub.prototype.ultraProp = 2;

var o = new Sub();

console.log(o.ultraProp); //true를 출력

sub객체는 ultraProp을 갖고 있지 않습니다. Sub의 부모인 super, super의 부모인 Ultra가 갖고 있습니다.

생성자는 기본적으로 함수입니다. 함수를 호출할 때 new를 붙이면 단순한 함수가 아닌 생성자 함수가 됩니다. 새로운 객체를 만들어 리턴합니다. o라는 변수는 sub()라는 생성자 함수에 의해 만들어진 객체입니다. 빈 객체를 만드는 것이 생성자라면 의미가 없습니다. 어떠한 객체를 만들 때 객체가 갖고 있어야하는 메소드, property값을 가져야합니다.

var o = new Sub();

//o.ultraProp = 1;

console.log(o.ultraProp); //2를 출력

1. 객체 o에서 ultraProp를 찾습니다..

2. 없다면 Sub.prototype.ultraProp를 찾습니다.

3. 없다면 Super.prototype.ultraProp를 찾습니다.

4. 없다면 Ultra.prototype.ultraProp를 찾습니다.

이는 객체와 객체를 연결하는 체인의 역할을 하는 것입니다. 이러한 관계를 prototype chain이라고 합니다.


출처 : 생활코딩 강의

728x90
반응형
728x90
반응형

+ Recent posts