절차적 언어

초기의 프로그래밍 언어는 일반적으로 절차적 언어라고 부름(C, 포트란 등)

절차적 언어는 순차적인 명령의 조합

 

객체 지향 언어

"클래스"라고 부르는 데이터 모델의 청사진을 사용해 코드 작성

현대의 언어들은 대부분 객체 지향의 특징을 갖고 있음(대표적으로 Java, C++, C# 등)

JavaScript: 객체 지향으로 작성 가능

예시

 

 

클래스와 인스턴스

클래스는 일종의 원형, 객체를 생성하기 위한 아이디어나 청사진

인스턴스는 클래스의 사례

클래스는 객체를 만들기 위한 생성자 함수를 포함

 

객체는 일반적인 함수를 정의하듯 만드는데

그냥 실행하는 것은 아니고,

new 키워드를 사용해서 만든다.(이는 새로운 인스턴스를 만드는 방법)

일반적인 다른 함수와 구분하기 위해 클래스는 보통 대문자로 시작하며 일반명사.
일반적인 함수는 적절한 동사를 포함하고 소문자로 시작

이때 예시로

속성은 brand, name, color, currentFuel, maxSpeed가 될 수 있고,

메소드는 refuel(), setSpeed(), drive() 가 될 수 있다.

 

ES5 클래스와, ES6 클래스 작성 문법은 조금 다른데 최근에는 ES6 방법을 주로 사용한다

 

ES5는 prototype이라는 키워드를 사용해야 메서드를 정의할수 있기에.
Car 클래스에 메서드를 추가하기 위해서는 Car.prototype.refuel과 같이 prototype을 이용해야 한다.


ES6에서는 생성자 함수와 함께 class 키워드 안쪽에 묶어서 정의
refuel() {}, drive() {}와 같이 작성되어 있는 부분이다.

.

 



클래스 문법을 이용한 카운터 만들기 예제

class Counter {
  constructor() {
    this.value = 0; // 생성자 호출을 할 경우, this는 new 키워드로 생성한 Counter의 인스턴스입니다
  }
  increase() {
    this.value++
  }
  decrease() {
    this.value--
  }
  getValue() {
    return this.value
  }
}

let counter1 = new Counter() // 생성자 호출
counter1.increase()
counter1.getValue() // 1

document.createElement('div')

//div 요소 생성

const tweetDiv = document.createElement('div')
//tweetDiv에 div 요소 넣기


document.body.append(tweetDiv)
//바디에 tweetDiv를 추가


const oneTweet = document.querySelector('.tweet')

const tweets = document.querySelectorAll('.tweet')
//이렇게 가져온 요소들은 '배열이 아닌 유사배열'
정식 명칭은 Array-like-Object

getElementById와 quertSelector은 같은 의미이고,
이전 브라우저 호환성 떄문에 전자를 사용해야 할수도 있다.

container.append(tweetDiv)
//컨테이너에 tweewDiv를 추가

extContent를 사용해서, 비어있는 div 엘리먼트에 문자열을 입력
ex) oneDiv.textContent

oneDiv.classList.add('tweet')
//CSS 스타일링이 적용될 수 있도록, div 엘리먼트에 class를 추가

const container = document.querySelector('#container')
container.append(oneDiv)
// append를 이용해 container의 자식 요소로 추가

oneDiv.remove()
//remove를 활용해 삭제하기

document.querySelector('#container').innerHTML = '';
//컨테이너의 모든 자식 요소를 지우기
+주의사항:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations


따라서 아래와 같은 removeChild 사용을 권고
const container = document.querySelector('#container');
while (container.firstChild) {
  container.removeChild(container.firstChild);
}
//자식 요소가 남아있지 않을 때까지, 첫 번째 자식 요소를 삭제하는 코드

const container = document.querySelector('#container');
while (container.children.length > 1) {
  container.removeChild(container.lastChild);
}
//제목까지 삭제되기에 이를 방지하는 코드

const tweets = document.querySelectorAll('.tweet')
tweets.forEach(function(tweet){
    tweet.remove();
})
// or
for (let tweet of tweets){
    tweet.remove()
}
//직접 클래스 이름을 찾아서 지우는 방법



ex)

let elInputUsername = document.querySelector('#username');
elInputUsername.value = '김코딩'
let elSuccessMessage = document.querySelector('.success-message hide');
let elFailureMessage = document.querySelector('.failure-message hide');
elFailureMessage.classList.remove('hide');
elInputUsername.onkeyup = function(){
  console.log(elInputUsername.value);
  if(isMoreThan4Length(elInputUsername.value)){
    console.log('4글보자보다 크네');
  }else{
    console.log('짧다');
  }
}
function isMoreThan4Length(value){
  return value.length >=4;
}

01_Introduction

 

it('Matcher .equal 의 사용법을 학습.', function () {
    let expectedValue = 2;
    expect(1 + 1).to.equal(expectedValue);
  });

  it('Matcher .equal의 사용법을 학습.', function () {
    let actualValue = (1 + 1).toString();
    expect(actualValue).to.equal('2'); 
  });

 

02_Types-part1

 

it('expect의 전달인자로 들어간 표현식의 평가(evaluation) 결과를 예측.', function () {
    expect(1 + '1').to.equal('11');
  });

  it('expect의 전달인자로 들어간 표현식의 평가(evaluation) 결과를 예측.', function () {
    expect(123 - '1').to.equal(122);
  });

  it('expect의 전달인자로 들어간 표현식의 평가(evaluation) 결과를 예측.', function () {
    expect(1 + true).to.equal(2);
  });

  it('expect의 전달인자로 들어간 표현식의 평가(evaluation) 결과를 예측.', function () {
    expect('1' + true).to.equal('1true');
  });

잘못된 값들이라는 것만 인지하고 다 외울 필요는 없다.

 

03_LetConst

it("'const'로 선언된 변수에는 재할당(reassignment)이 금지됨.", function () {
    const constNum = 0;
    expect(constNum).to.equal(0);

    const constString = 'I am a const';
    expect(constString).to.equal('I am a const');
  });

  it("'const'로 선언된 배열의 경우 새로운 요소를 추가하거나 삭제할 수 있다.", function () {
    const arr = [];
    const toBePushed = 42;
    arr.push(toBePushed);
    expect(arr[0]).to.equal(42);
  });

  it("'const'로 선언된 객체의 경우, 속성을 추가하거나 삭제할 수 있다.", function () {
    const obj = { x: 1 };
    expect(obj.x).to.equal(1);
    delete obj.x;
    expect(obj.x).to.equal(undefined);
    obj.occupation = 'SW Engineer';
    expect(obj['occupation']).to.equal('SW Engineer');
  });

 

04_Scope

it('lexical scope와 closure에 대해 다시 확인.', function () {
    let age = 27;
    let name = 'a';
    let height = 179;

    function outerFn() {
      let age = 24;
      name = 'b';
      let height = 178;

      function innerFn() {
        age = 26;
        let name = 'c';
        return height;
      }

      innerFn();

      expect(age).to.equal(26);
      expect(name).to.equal('b');

      return innerFn;
    }

    const innerFn = outerFn();

    expect(age).to.equal(27);
    expect(name).to.equal('b');
    expect(innerFn()).to.equal(178);
  });

 

05_ArrowFunction

  it('화살표 함수를 이용하여 클로저를 표현', function () {
    const adder = x => {
      return y => {
        return x + y
      }
    }

    expect(adder(50)(10)).to.eql(60)

    const subtractor = x => y => {
      return x - y
    }

    expect(subtractor(50)(10)).to.eql(40)

    const htmlMaker = tag => textContent => `<${tag}>${textContent}</${tag}>`
    expect(htmlMaker('div')('code states')).to.eql('<div>code states</div>');

    const liMaker = htmlMaker('li')
    expect(liMaker('1st item')).to.eql('<li>1st item</li>');
    expect(liMaker('2nd item')).to.eql('<li>2nd item</li>')
  })

 

06_Types-part2

it('참조 자료형을 변수에 할당할 경우, 데이터의 주소가 저장됨.', function () {
    const overTwenty = ['a', 'b', 'c']; 
    let allowedToDrink = overTwenty

    overTwenty.push('d');
    expect(allowedToDrink).to.deep.equal(['a', 'b', 'c', 'd']);
    overTwenty[1] = 'e';
    expect(allowedToDrink[1]).to.deep.equal('e');

    const ages = [22, 23, 27];
    allowedToDrink = ages;
    expect(allowedToDrink === ages).to.equal(true);
    expect(allowedToDrink === [22, 23, 27]).to.equal(false);

    const nums1 = [1, 2, 3];
    const nums2 = [1, 2, 3];
    expect(nums1 === nums2).to.equal(false);
//ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ//
    const person = {
      son: {
        age: 9,
      },
    };

    const boy = person.son;
    boy.age = 20;
    expect(person.son.age).to.equal(20);
    expect(person.son === boy).to.equal(true);
    expect(person.son === { age: 9 }).to.equal(false);
    expect(person.son === { age: 20 }).to.equal(false);

 

07_Array

it('Array를 함수의 전달인자로 전달할 경우, reference가 전달됨.', function () {
    const arr = ['zero', 'one', 'two', 'three', 'four', 'five'];

    function passedByReference(refArr) {
      refArr[1] = 'changed in function';
    passedByReference(arr);
 
    expect(arr[1]).to.equal('changed in function');

    const assignedArr = arr;
    assignedArr[5] = 'changed in assignedArr';
    expect(arr[5]).to.equal('changed in assignedArr');

    const copiedArr = arr.slice();
    copiedArr[3] = 'changed in copiedArr';
    expect(arr[3]).to.equal('three');
  });

  it('Array 메소드 shift와 unshift를 확인.', function () {
    const arr = [1, 2];

    arr.unshift(3);
    expect(arr).to.deep.equal([3, 1, 2]);

    const shiftedValue = arr.shift();
    expect(shiftedValue).to.deep.equal(3);
    expect(arr).to.deep.equal([1, 2]);
  });

 

08_Object

it('Object를 함수의 전달인자로 전달할 경우, reference가 전달됨.', function () {
    const obj = {
      mastermind: 'Joker',
      henchwoman: 'Harley',
      relations: ['Anarky', 'Duela Dent', 'Lucy'],
      twins: {
        'Jared Leto': 'Suicide Squad',
        'Joaquin Phoenix': 'Joker',
        'Heath Ledger': 'The Dark Knight',
        'Jack Nicholson': 'Tim Burton Batman',
      },
    };

    function passedByReference(refObj) {
      refObj.henchwoman = 'Adam West';
    }
    passedByReference(obj);
    expect(obj.henchwoman).to.equal('Adam West');

    const assignedObj = obj;
    assignedObj['relations'] = [1, 2, 3];
    expect(obj['relations']).to.deep.equal([1, 2, 3]);

    const copiedObj = Object.assign({}, obj);
    copiedObj.mastermind = 'James Wood';
    expect(obj.mastermind).to.equal('Joker');

    obj.henchwoman = 'Harley';
    expect(copiedObj.henchwoman).to.equal('Adam West');

    delete obj.twins['Jared Leto'];
    expect('Jared Leto' in copiedObj.twins).to.equal(false);

    /*
 
    이와 관련하여 얕은 복사(shallow copy)와 깊은 복사(deep copy)에 대해
 
    */
  });

 

09_SpreadSyntax

 

빈 배열에 전개 문법을 사용할 경우, 아무것도 전달되지 않음

여러 개의 배열을 이어 붙일 수 있음

여러 개의 개체를 병합할 수 있음

Rest Parameter는 함수의 전달인자를 배열로 다룰 수 있게 함

Rest Parameter 전달인자의 수가 정해져 있지 않은 경우에도 유용하게 사용 가능

it('Rest Parameter는 전달인자의 일부에만 적용할 수도 있습니다.', function () {
    // rest parameter는 항상 배열입니다.
    function getAllParams(required1, required2, ...args) {
      return [required1, required2, args];
    }
    expect(getAllParams(123)).to.deep.equal([123, undefined, []]);

    function makePizza(dough, name, ...toppings) {
      const order = `You ordered ${name} pizza with ${dough} dough and ${toppings.length} extra toppings!`;
      return order;
    }
    expect(makePizza('original')).to.equal(`You ordered undefined pizza with original dough and 0 extra toppings!`);
    expect(makePizza('thin', 'pepperoni')).to.equal(`You ordered pepperoni pizza with thin dough and 0 extra toppings!`);
    expect(makePizza('napoli', 'meat', 'extra cheese', 'onion', 'bacon')).to.equal(`You ordered meat pizza with napoli dough and 3 extra toppings!`);
  });
});

 

10_Destructuring

it('rest/spread 문법을 객체 분해에 적용할 수 있다', () => {
    const user = {
      name: '김코딩',
      company: {
        name: 'Code States',
        department: 'Development',
        role: {
          name: 'Software Engineer'
        }
      },
      age: 35
    }

    const changedUser = {
      ...user,
      name: '박해커',
      age: 20
    }

    const overwriteChanges = {
      name: '박해커',
      age: 20,
      ...user
    }

    const changedDepartment = {
      ...user,
      company: {
        ...user.company,
        department: 'Marketing'
      }
    }

    expect(changedUser).to.eql({
      name: '박해커',
      company: {
        name: 'Code States',
        department: 'Development',
        role: {
          name: 'Software Engineer'
        }
      },
      age: 20
    }
     
    )

    expect(overwriteChanges).to.eql(
      {
        name: '김코딩',
        company: {
          name: 'Code States',
          department: 'Development',
          role: {
            name: 'Software Engineer'
          }
        },
        age: 35
      }
    )

    expect(changedDepartment).to.eql(
      {
        name: '김코딩',
        company: {
          name: 'Code States',
          department: 'Marketing',
          role: {
            name: 'Software Engineer'
          }
        },
        age: 35
      }
    )
  })

+ Recent posts