Programming/JavaScript

변수, 함수, this, 생성자

녱녱 2022. 11. 14.

개인 공부한 내용입니다!

오류가 있다면 알려주시면 감사하겠습니다:)

JavaScript

변수(변수의 데이터 값을 저장하는 컨테이너)

  • 변수의 선언은 var 키워드 사용, var는 함수 스코프
    • 변수명 규칙 : 문자/숫자/_/$ 사용 가능, 소문자로 시작, 대소문자 구분, 예약어 사용 금지
    • let : 재선언 불가, 재할당 가능, block/함수 스코프
    • const : 재선언/재할당 불가 -> 선언 동시에 할당, block/함수 스코프
  • 다양한 데이터 타입 설정 가능(자동 설정)
  • 한 문장에 comma(,)를 사용 해 여러 변수 선언 가능
  • 다시 선언된 변수는 그 값을 유지
  • 연산 가능
    • 숫자를 문자로 연산하면 숫자는 문자열로 다뤄짐

 

Function

  • function name() {}
  • 함수명에는 문자, 숫자, _, $ 사용 가능
  • 괄호 내에 comma에 의해 분리된 파라미터 명을 표함할 수 있고 실행코드는 {} 내에 작성
  • 실행코드는 무언가에 의해 호출될 때 실행
    • 이벤트가 실행 될때, JS 코드로부터 호출될 때, 자동적으로(스스로 호출)
    • return문에 도달시 함수는 실행이 중단되고 함수를 호출한 곳으로 값을 보냄
  • 함수를 변수로도 사용 가능
  • 선언법
    • 선언문 : function name(){}
    • 표현식 : var name = function(){};
    • 생성자 : var name = Funtion('a', 'b', 'return a+b');

This

  • this를 동적으로 바인딩하지 않는다면 호출 객체 내 this는 .앞의 객체가 됨, 없다면 Window 혹은 undefined
  • 전역에서 this : window를 가르킴
console.log(this); /*Window*/
  • 객체 내 메소드 : 자기 자신(obj를 가리킴)
const obj = {
    a: "a",
    func: funtion(){
    console.log(this);
    }
}
obj.func();
  • 생성자 내 : 자기 자신(Test)이 바인딩
    • 바인딩 : 프로그램에서 사용된 구성 요소의 실제값 또는 프로퍼티를 결정 짓는 행위
function Test(){
    this.a = "a";
    this.b = "b";
    console.log(this);/*Test*/
}
const c = new Test();
  • Class 생성자/메소드 내 : 자기 자신(Test Class)이 바인딩
class Test{
    constructor(){
        this.a="a";
        this.b="b";
        console.log(this);
    }
    testMethod(){
        console.log(this);
    }
    const t = new Test();
    t.testMethod();
}
  • 화살표 함수 내 : 상위 스코프의 this가 화살표 함수 내 this로 바인딩
function Test1(){
    this.a = "a";
    this.b = "b";
    const func1 = function(){
        console.log(this);/*Window*/
    }
    const func2 = () => {
        console.log(this);/*Test1*/
    }
    func1();
    func2();
}
function Test2(){
    this.a = "a";
    this.b = "b";
    const func1 = function(){
        console.log(this);/*undefined*/
    }
    const func2 = () => {
        console.log(this);/*Test2*/
    }
    func1();
    func2();
}
const t1 = new Test1();
const t2 = new Test2();
  • 함수 표현식, 선언문 내 : 전역(Window)이 바인딩
    • "use strict";가 선언되면 window 객체가 자동으로 바인딩되지 않음
  • 내부함수 내 : 전역(Window) 바인딩
    • "use strict"; 선언시 undefined
  • apply, call, bind를 활용해 동적으로 this를 바인딩 가능
    • call : 첫번째 매개변수로 thisArg를 넘겨주고 파라미터 그대로 사용, this 바인딩만 하고 함수를 호출
      • fun.call(thisArg[, arg1[, arg2 ...]])
    function Obj(name, age){
        this.name = name;
        this.age = age;
    }
    
    Obj.prototype.print = function(){
        console.log('name : '+this.name+' age : '+this.age);
    }
    
    var student1 = new Obj('철수', '20');
    student1.print();
  • apply : 매개변수의 전달방식이 배열, this 바인딩만 하고 함수를 호출
    • fun.apply(thisArg, [argsArray])
  • bind : 함수 호출 X, 새로운 함수를 만들어 return -> so, 바로 함수가 호출되지 않음
    • func.bind(thisArg[, arg1[, arg2[, ...]]])
  • addEventListener callback 함수 내 this : 해당 요소가 바인딩
const input = document.getElementById("input");
input.addEventListener("click", function(e){
    console.log(this);/*input*/
});

생성자

  • 인스턴스(메모리상에 존재하게 하는) 객체를 생성하고 초기화 하는 함수
  • new 연산자 사용
function Student(data){
    this.name = data.name;
    this.age = data.age;
}
const aStudent = new Studen({name:"young", age : 25});
console.log(aStudent)
  • class 키워드 사용
class Student{
    constructor(data){
        this.name = data.name;
        this.age = data.age;
    }
}
const aStudent = new Student({name:"young", age : 25});
console.log(aStudent);    
  • ex1) 공통함수 추가
/*new 연산자 활용*/
function Student(data){
    this.name = data.name;
    this.age = data.age;
    this.getName = function(){
        return this.name;
    }
}
const aStudent = new Student({name:"young", age:35})
console.log(aStudent.getName());
/*class 키워드 활용*/
class Student{
    constructor(data){
        this.name = data.name;
        this.age = data.age;
        this.getName = function(){
            return this.name;
        }    
    }
};
const aStudent = new Student({name:"young", age:25});
console.log(aStudent.getName());
  • 메모리 낭비를 막기 위해 객체에 공통으로 사용되는 함수는 prototype으로 사용
function Student(data){
    this.name = data.name;
    this.age = data.age;
}
Student.prototype.getName = function(){
    return this.name;
}
class Student{
    constructor(data){
        this.name = data.name;
        this.age = this.age;
    }
    getName(){
        return this.name;
    }
}

반복문

  • for : index 리턴
  • for in : index 리턴, object에서도 사용 가능
  • for each : 해당 값 리턴
  • for of : 해당 값 리턴

'Programming > JavaScript' 카테고리의 다른 글

JS 동작 원리 / 비동기 동작  (0) 2022.11.16

댓글