본문 바로가기
Web/js

JavaScript(1)

by ormgm 2020. 2. 4.

- 스크립트 언어

: 어떤 어플리케이션에서 그 코드를 해석하고 실행할 수 있는 엔진이 존재하여 그 스크립트로 해당 어플리케이션을 제어하기 위한 용도로 사용되는 프로그래밍 언어

 

- 인터프리터 언어

: 소스코드를 한 줄씩 읽으면서 해석

 

- 다양한 런타임 환경

: 각종 웹브라우저, Node,js, Electron 등

 

자바스크립트는 많은 분야(웹 프론트엔드, 백엔드, 데스크탑, 모바일 등)에서 사용된다.

 

 

실습 준비

1. chrome

2. node.js

3. vscode

 

vscode로 코드를 작성한 후 cmd를 통해 코드가 작성된 파일이 있는 폴더로 가서 

node 파일명.js 을 입력하면 명령이 실행된다.

 

 

표현식(Expression)

: 값을 만들어내는 간단한 코드를 표현식이라고 한다.

ex)

true, false, 숫자, 1000+900+90+4(1994를 만들어내는 표현식), "Anna", "Anna" + "is"(Anna is를 만들어내는 표현식)

 

 

키워드(Keywords)

: 자바스크립트에-서 특정한 목적을 위해 사용하는 단어로 이러한 키워드들은 예약어로 지정되어 있다.

* 예약어 : 프로그램을 작성할 떄, 변수명, 함수명 등 이름으로 사용할 수 없는 단어

 

 

식별자(Identifier)

: 코드 내의 변수, 함수, 혹은 속성을 식별하는 문자열 ( 함수, 변수의 이름을 말한다.)

 

const

: 상수를 지칭하는 이름으로 상수를 선언하면서 바로 값을 할당 해야함

 

let

: 변수를 지칭하는 이름

 

const,let = 블록 스코프

var = 함수 스코프 (

 

 

즉시 실행 함수 사용법

( function(){

 

}) ()

 

 

호이스팅(Hoisting)

: 아래 있는 선언을 끌어올리는 것 

문제점 : var을 사용해 아래에 선언한 변수의 선언부도 끌어올림

 

 

동적 타이핑

: 자바스크립트는 느슨한 타입 언어, 혹은 동적 언어이다. 즉, 변수의 타입을 미리 선언할 필요가 없고 프로그램이 처리되는 과정에서 자동으로 파악한다는 뜻이고, 같은 변수에 여러 타입의 값을 넣을 수 있다는 뜻이다.

* 변수가 가지는 고정 타입이 없다. ( 타입이 없는 것은 아님)

 

 

데이터 타입

1. 기본 타입(primitive type)

 -boolean

 -null

 -Undefined

 -Number

 -string

 -Symbol 

* null과 Undefined는 if문에서 ==으로 비교할 시 같다고 나오기 때문에 ===으로 비교해야한다.

* 만들어진 Symbol은 고유한 것으로 Symbol과 다른 Symbol을 ===으로 비교 시 같지 않다고 나온다. 

2. 객체 

 

변수의 데이터 타입 알아보는 법

console.log(typeof 변수명)

 

템플릿 스트링 사용법

const a = 'kim'

const d = `${a} 'lee'`;

=> kim lee 

 

표현식이 거짓으로 평가될 때 (Falsy한 값)

1.false

2. 0

3. null

4. ''

5. undefined

6. Nan

 

표현식이 참으로 평가될 때  (Truethy한 값)

1. true

2. 0이아닌 모든 숫자

2. '문자열'

3. {}

4. []

 

for of

: iterable한 객체(배열)에 모두 사용할 수 있음

for(const i of [1, 2 ,3]){

 

}

 

for in

: 객체 안에 있는 프로퍼티 하나하나를 사용할 수 있음

for( const i in { a: 1, b: 2, c: 3}) {

 

}

 

for in과 for of의 차이점

1. for in은 객체의 모든 열거 가능한 속성에 대한 반복

2. for of는 [Symbol.iterator] 속성을 가지는 컬렉션에 대한 반복

 

 

선언적 function

function 함수이름( ){

 

}

* 함수도 객체의 한 종류

 

익명함수를 만들어 변수에 할당

const 변수이름 =  function(){

 

}; 

=>typeof 사용해서 보면 function임

 

둘의 차이점 

: 선언적은 함수를 함수를 먼저 메모리에 올리는 것으로 호이스팅이 발생

 

생성자 함수로 함수 생성

const 변수이름 = new Function(); //잘 쓰이지는 않음

const sum = new Function('a', 'b', 'c', 'return a + b + c');

 

arrow function

const hello = ( 인자) => {

 console.log('hello');

} ;

 

const hello2 = name => { // 인자가 하나일 때는 괄호 생략가능

 console.log('hello2',name);

};

 

const hello5 = name => `hello ${name}`; // return문 하나일 경우 중괄호 생략가능

* this가 생성되지 않음 

*생성자 함수를 사용해 만드는 객체는 선언적 function으로 만들어야함

 

 

함수를 이용한 함수 만들기

function plus(base){

    return function(num){

        return base + num;

 

    };

}

 

const plus5 = plus(5);

console.log(plus5(10))

 

const plus7 = plus(7);

console.log(plus7(8));

 

함수를 인자로하여 함수를 호출하기

function hello(c){

    console.log('hello');

    c();

}

 

hello(function(){

    console.log('콜백');

});

 

객체, 개체, object(모두 동일)

: 함수나 클래스와 같은 틀로 만들어지는 것

 

객체 만들기

function a(){}

const a = new a();

 

const b = new Object(); //  잘 사용하지 않음

 

프로토타입 체인

: 모든 객체들을 연결해서 표현할 수 있도록 한 것으로 프로토타입은 객체의 원형이라고 할 수 있다.

- 일반적인 객체지향 언어와 구분지을 수 있는 것

 

객체 리터럴

const a = {}

=>a를 typeof 해보면 object로 나옴

 

const c = {

    name: 'Mark',

    hello1() {

        console.log('hello1'this.name); // this가 c객체를 가리킴

    },

    hello2: function() {

        console.log('hello2'this.name);  // this가 c객체를 가리킴

    },

    hello3: () => {

        console.log('hello3'this.name); // // this가 c객체를 가리키지 않음

    }

};

 

 

표준 내장 객체

: 이미 런타임 환경에 만들어져 있는 객체 

1. Array

const a = new Array('red', 'black', 'white')

const b = ['red', 'green', 'yellow'];

=> typeof 해보면 object로 나옴

      Array의 인스턴스이기도 하지만 object의 인스턴스이기도 하다

 

 

클래스

: 객체를 만들 수 있는 새로운 방법으로 기존의 프로토타입 기반의 상속 보다 명료하게 사용할 수 있도록 도와준다.

 

클래스 생성 방법

1. 선언적 방식

class A {}

console.log(new A());

* 선언적방식이지만 호이스팅이 일어나지 않는다.

2. 클래스 표현식을 변수에 할당

const B = class {};

console.log(new B());

 

 

생성자(constructor)

class C {

    constructor(name, age){

        console.log('constructor', name, age);

    }

}

console.log(new C('Kim',25));

 

 

클래스안에 멤버변수(property)생성하기

class A{

    constructor(name,age){

        this.name = name;

        this.age = age;

    }

}

console.log(new A('Kim',25));

 

class B{

    name;

    age;

}

console.log(new B());

 

class C {

    name = 'no name';

    age = 0;

    constructor(name, age) {

        this.name = name;

        this.age = age;

    }

}

console.log(new C('kim',25));

 

 

클래스 안에 멤버 함수 생성하기

class A{

    hello(){

        console.log('hello',this);

    }

    hello2 = () => {

        console.log('hello2',this);

    }

}

new A().hello();

new A().hello2();

 

class B {

    name = 'kim';

 

    hello(){

        console.log('hello',this.name)

    }

}

new B().hello();

 

 

Getter,Setter

class A{

    _name = 'no name'; // 내부적으로 사용할 경우 _를 씀

 

    get name() {

        return this._name + '@@@';

    }

    set name(value){

        this._name = value+'!!!';

    }

}

 

const a = new A();

console.log(a);

a.name = 'Kim'; //Kim이 value자리에 들어감

console.log(a);

console.log(a.name); // getter의 결과

console.log(a._name); // setter의 결과

 

class B{

    _name = 'no name'; // 내부적으로 사용할 경우 _를 씀

 

    get name() {

        return this._name + '@@@';

    }

}

const b = new B();

console.log(b);

b.name = 'Kim';

console.log(b); // setter함수가 없기때문에 readonly처럼 작동

 

 

static  변수, 함수

: 클래스를 통해서 직접적으로  변수와 함수를 사용하는 방식으로 스태틱 함수는 클래스 함수라고도 부른다.

class A{

    static age = 37;

    static hello(){

        console.log(A.age); 

    }

}

console.log(A,A.age);

A.hello();

 

class B{

    age = 37;

    static hello(){

        console.log(this.age)

    }

}

 

console.log(B, B.age)

B.hello();

//new B().hello(); 객체에 속한 함수가 아니기 때문에 컴파일러 타입 에러 출력

 

class C{

    static name = '이 클래스의 이름은 C가 아니다.'; 

    //static name은 class의 이름을 뜻하기때문에 'function C'라고 나오지 않고 'function 이 클래스의 이름은 C가 아니다.'로 나온다  

 

}

console.log(C)

 

 

extends 클래스 상속 기본

class Parent{

    name = 'Lee';

 

    hello(){

        console.log('hello',this.name);

    }

}

 

class Child extends Parent{

 

}

 

const p = new Parent();

const c = new Child();

console.log(p,c);

 

c.hello();

c.name = 'Anna';

c.hello();

 

 

override 클래스의 상속 멤버 변수 및 함수 추가 및 오버라이딩

부모와 똑같은 함수이름을 사용하는 것을 오버라이딩이라고 한다.

class Parent{

    name = 'Lee';

 

    hello(){

        console.log('hello', this.name);

    }

}

 

class Child extends Parent{

    age = 37;

 

    hello(){ //오버라이딩

        console.log('hello',this.name, this.age);

    }

}

 

const p = new Parent();

const c = new Child;

 

console.log(p, c);

c.hello();

c.name = 'Anna';

c.hello();

 

 

super 클래스의 상속 생성자 함수 변경

: 자식이 생성체에 뭔가를 추가하고자할 때 꼭 필요함

class Parent{

    name;

    constructor(name) {

        this.name = name// *** 

    }

 

    hello(){

        console.log('hello',this.name);

    }

}

 

class Child extends Parent{

    age;

    constructor(name,age){

        super(name); //super는 ***을 가리킨다.

        this.age = age;

    }

 

    hello(){

        console.log('hello',this.name,this.age);

    }

}

 

const p = new Parent('Kim');

const c = new Child('Kim',25);

 

console.log(pc);

c.hello();

 

 

클래스의 static상속

class Parent{

    static age = 37;

}

 

class Child extends Parent{

 

}

 

console.log(Parent.age,Child.age);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Web > js' 카테고리의 다른 글

인사이드 자바스크립트  (0) 2020.03.10
JavaScript(2)  (0) 2020.02.06

댓글