leebom
#011 자바스크립트 200제 - static, this, module 본문
클래스 정적 메소드(static) & 속성 정의
- 일반적인 클래스는 해당 클래스의 인스턴스를 통해 호출하지만 정적 메소드는 클래스를 통해 직접 호출하는 메소드를 말함
- 정적 메소드는 static 키워드 와 get 키워드를 사용하여 정의
class Product {
//static를 이용하여 build 메소드를 정의
static build(name, price) {
const id = Math.floor(Math.random() * 1000);
return new Product(id, name, price);
}
static getTaxPrice(product) {
return (product.price * 0.1) + product.price;
}
constructor(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
}
class DeposableProduct extends Product {
depose() {
this.depose = true;
}
}
const gum = Product.build('껌', 1000);
console.log(gum); // Product {id: 407, name: "껌", price: 1000}
const clothes = new DeposableProduct(1, '옷', 2000);
const taxPrice = DeposableProduct.getTaxPrice(clothes);
console.log(taxPrice); //2200
-static get 키워드를 통해 정의
class ProductWithCode {
static get CODE_PREFIX() {
return "PRODUCT-"
}
constructor(id) {
this.id
this.code = ProductWithCode.CODE_PREFIX + id;
}
}
const product1 = new ProductWithCode('001');
console.log(ProductWithCode.CODE_PREFIX); // PRODUCT-
console.log(product1.code); //PRODUCT-001
this 키워드
- this는 전역에서 사용살수있고 함수안에서도 사용가능
함수는,
- ① 객체안에 메소드로 정의
- ② 생성자 함수로 사용
- ③ 특정 로직을 계산하여 값을 반환하는 목적으로 사용
그에 따라 this도 각 함수별로 다르게 해석될수 있음
this.valueA = 'a';
console.log(valueA); //a
valueB = 'b';
console.log(this.valueB); //b
//브라우저환경에서 this를 전역에서 사용하면 전역객체인 Window를 가르킴
function checkThis() {
console.log(this) //window
}
//use strict를 사용하여 더 까다롭게 보면 undefinded
function checkThis2() {
"use strict";
console.log(this); // undefinded
}
checkThis();
checkThis2();
//생성자 함수로 작성
function Product(name, price) {
this.name = name;
this.price = price;
}
// new키워드 없이 호출했을때는 전역객체인 Window를 가르킴
const product1 = Product('가방', 2000);
console.log(window.name); //가방
console.log(window.price); //2000
const product2 = {
name: "가방2",
price: 3000,
getVAT() {
//정의된 함수인 메소드 안에서 this를 사용하고 그객체를 통해 메소드를 호출하면 this는 그 객체를 가르킴
return this.price / 10;
}
}
const valueOfProduct2 = product2.getVAT();
console.log(valueOfProduct2); // 300
const calVAT = product2.getVAT;
const VAT2 = calVAT();
console.log(VAT2); // 200
//bind메소드를 통해 전달한 인자값으로 변경
const newCalVAT = calVAT.bind(product2);
const VAT3 = newCalVAT();
console.log(VAT3); //300
const counter1 = {
count: 0,
addAfter1Sec() {
setTimeout(function() {
this.count += 1; //this.count가 window.count로 해석됨 ->undefinded
console.log(this.count); //NaN
}, 1000)
}
};
counter1.addAfter1Sec();
const counter2 = {
count: 0,
addAfter1Sec() {
setTimeout(function() {
this.count += 1;
console.log(this.count); //1
}, 1000)
}
}
counter2.addAfter1Sec();
- 브라우저환경에서 this를 전역에서 사용하면 전역객체인 Window를 가르킴
모듈(moudule)
- 파일이나 코드의 묶음 단위로 애플리케이션의 하나의 구성요소로 볼 수 있음.
- 모듈로 정의하면 모듈단위로 코드를 재사용 할수있고, 큰 기능을 작은 기능단위로 분리하여 관리할 수 있음.
#네임 스페이스 패턴
- 네임스페이스란 c#언어에서 제공하는 기능으로 코드를 그룹화하고 이름 충돌을 방지하게 도와줌.
그러나 자바스크립트에서는 직접적으로 지원하지않기 때문에 함수를 정의함과 동시에 실행하는 즉각 호출 패턴을 통해 네임스 페이스를 유사하게 할수있음. 이렇게 하는 이유는 기본적으로 변수와 함수를 선언하게 되면 전여긍로 정의되어 다른 라이브러리 나 타인의 코드에서 정의된 이름들과 충돌이 날수 있기 때문
//즉각 호출 패턴 : (fucntion(){//......})();
var namespaceA = (function() {
var privateVariable = '비공개변수';
return {
publicApi: function() {
console.log(privateVariable + '를 접근할 수 있습니다.');
}
}
})();
namespaceA.publicApi();
//비공개변수를 접근할 수 있습니다.
#export 키워드
- 모듈 내의 특정 코드를 외부에서 사용할수 있음
export function hello(name) {
console.log(`Hello ${name}`);
}
#Import 키워드
- Import 키워드를 이용해서 export한 코드들을 가져올 수 있음
import {hello} from './hello.js';
hello('es6 module'); // Hello es6 module
# 모듈의 기본값 default
- 하나의 모듈에서 한번만 사용가능, 즉 한파일에서 하나의 값만 default로 정의할수 있음
export default function hello(name) {
console.log('hello ' + name);
};
'스터디 > 개인스터디' 카테고리의 다른 글
#013 자바스크립트 200제 - 문자열, 숫자형, 자료형 변환 (0) | 2020.12.14 |
---|---|
#012 자바스크립트 200제 - 모듈, 내장함수객체, 자료형 (0) | 2020.12.13 |
#010 자바스크립트 200제 - Arrow function, 객체지향 프로그래밍, 생성자 함수, 클래스 정의 (0) | 2020.12.11 |
#009 자바스크립트 200제 - 스코프체인 (0) | 2020.12.10 |
#008 자바스크립트 200제 - 함수의 매개변수 & 변수선언 (0) | 2020.12.09 |