정의

어떤 목적을 이루기 위해서 여러가지 전략 중에서 한 가지를 선택하여 사용해야 하는 상황을 해결 하기 위한 디자인 패턴

OCP를 만족하면서 새로운 전략을 추가하고 싶을 때 사용 됨

 

OCP 가 지켜지지 않은 예제

CartForSongs

import java.util.ArrayList;
import java.util.List;

class Song {
    private String discountMode;
    private int price;
		public Song(String discountMode, int price){
			this.discountMode = discountMode;
			this.price = price;
		}
    public String getDiscountMode() {
        return discountMode;
    }
    public double getPrice() {
        return price;
    }
}

public class CartForSongs {
    List<Song> cart = new ArrayList<>();
    public double calculateTotalPrice(){
        double total = 0.0;
        for (Song song : cart) {
            if(song.getDiscountMode().equals("OnSale"))
                total = total + (song.getPrice()-0.1*song.getPrice());
            else if(song.getDiscountMode().equals("TodayEvent"))
                total = total + (song.getPrice()-0.3*song.getPrice());
            else if(song.getDiscountMode().equals("ChusukEvent"))
                total = total + (song.getPrice()-0.4*song.getPrice());
            else total = total + song.getPrice();
        }
        return total;
    }
    public void add(Song song) {
        cart.add(song);
    }
}
  • 해당 코드에 문제점 새로운 할인 모드가 추가되면 코드를 전체적으로 수정해야 한다.

1. 할인 정책 → 클래스 (변화의 단)

  • 변화의 단 식별 이후 클래스로 모델링

2. 포괄하는 개념 만들기

interface DiscountMode {
    public abstract double getDiscountRate();
}

class OnSale implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.1;
    }
}

class NoDiscount implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.0;
    }
}

class TodayEvent implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.3;
    }
}

public class Song {
    private double price;
    private String title;
    private DiscountMode discountMode;

    public Song(double price, String title) {
        this.price = price;
        this.title = title;
        this.discountMode = new NoDiscount();
    }
    public double getPrice(){
        return price - price*discountMode.getDiscountRate();
    }
    public void setDiscountMode(DiscountMode discountMode) {
        this.discountMode = discountMode;
    }
}
import java.util.ArrayList;
import java.util.List;

public class CartForSongs {
    private List<Song> cart = new ArrayList<>();
    public double calculateTotalPrice(){
        double total = 0.0;
        for (Song song : cart) total += song.getPrice();

        return 0.0;
    }
    public void add(Song song){
        cart.add(song);
    }
}
  • 새로운 할인 모드가 추가되어도 코드를 수정할 필요 없도록 개선됨

내용 요약

  • when: 어떤 목적을 이루기 위해서 여러가지 전략 중에서 한 가지를 선택하여 사용해야 하는 상황
  • how: OCP원칙이 지켜지게 끔 재설계
  • solve: 변화의 단 새로운 규칙이 추가되는 내용을 파악하여 abstract class or interface으로 정의
interface DiscountMode {
    public abstract double getDiscountRate();
}

class OnSale implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.1;
    }
}

class NoDiscount implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.0;
    }
}

class TodayEvent implements DiscountMode {
    @Override
    public double getDiscountRate() {
        return 0.3;
    }
}

'Development > Design Pattern' 카테고리의 다른 글

[Design Pattern] 싱글톤 패턴  (0) 2023.08.29

Thread

  • 선언: new Thread( run())
  • 실행: new Thread(run()).start(); run()함수 실행
  • 목적: 일을 더 빠르게 하기 위해
// Thread 생성과 동시에 실행
Thread thread = new Thread(() =>
    for(int i=0;i<4;i++){
        System.out.println("hellow world")
    }
).run();

synchronized

  • 동기화, 특정 객체에 lock이 걸려있는지 안 걸려있는지 체크 하여 작업
  • 구문: synchronized(객체)
  • 기능: 해당 객체에 lock이 걸려있는지 확인한다
    • 해당 객체에 lock이 안 걸려 있다면 걸고 실행
    • 해당 객체에 lock이 걸려 있다면 해제될때까지 기다린다.
  • 논 synchronized는 객체 lock이 걸려있든 걸려있지 않든 실행 시킨다.
// 두 함수는 동일한 기능
// 명시 되어 있지는 않지만 this 객체를 기준으로 lock을 검사함
public synchronized void print1(){
// to do
}

public void print2(){
    synchronized(this){
    // to do 
    }
}

Optional 객체

  • return null 을 통해 코드가 복잡해지는 걸 방지하기 위해 사용을 권장
  • .ifPresent(s→(System.out.println(”test”))): 해당 Optional 객체가 null이 아니라면 해당 내용을 실행해라

정의: 비동기(asynchronous)

  • 여러 작업이 동시에 실행되거나, 어떤 작업이 완료되기를 기다리지 않고 다음 작업을 시작하는 방식으로 주로 I/O 연산, 네트워크 요청에 유용하다.
const fs = require('fs);
console.log('start');

fs.readFile('./readme1.txt, (err, data)=>{
    if(err)
        console.error(err);
    else
        console.log('1st reading:', data.toString());
});
fs.readFile('./readme2.txt, (err, data)=>{
    if(err)
        console.error(err);
    else
        console.log('2st reading:', data.toString());
});
fs.readFile('./readme3.txt, (err, data)=>{
    if(err)
        console.error(err);
    else
        console.log('3st reading:', data.toString());
});
console.log('end');

<실행 결과>

start

end

이후 결과는 예상 불가능 동작의 순서가 cpu 스케쥴링에 따라 다르기 때문

이를 해결 하기 위한 비동기 매커니즘 방식

  • 콜백 (Callback)
  • promise 객체
  • Async/Await 구문

콜백 (Callback)

const fs = require('fs);
console.log('start');

fs.readFile('./readme1.txt, (err, data)=>{
    if(err)
        console.error(err);
    else{
        console.log('1st reading:', data.toString());
        fs.readFile('./readme2.txt, (err, data)=>{
            if(err)
                console.error(err);
            else
                console.log('2st reading:', data.toString());
                fs.readFile('./readme3.txt, (err, data)=>{
                    if(err)
                        console.error(err);
                    else
                        console.log('3st reading:', data.toString());
                    console.log('end');
                });
            }
        });
    }
});
  • 다음에 실행되어야 할 문장을 내부적으로 두면서 우선적인 작업이 완료되면 다음 작업이 실행 되도록 하는 방법
  • 장점: 기본적이며 가장 원시적인 방법이기에 대부분의 자바스크립트 환경에서 지원 받을 수 있다.
  • 단점: 가독성이 매우 떨어진다.

promise 객체

  • 정의: 비동기 방식으로 실행하지만 아직 결과를 반환하지 않은 객체 미래에 어떤 시점에 결과를 제공하겠다는 약속을 의미함 생성시 인수로 resolve(), reject()함수를 필요로 한다.
    • 성공: resolve(value)는 .then으로 연결
    • 실패: rejected(value)sms .catch로 연결
const promise = new Promise( (resolve, reject) =>{
    console.log('start');
        fs.readFile('./readme1.txt, (err, data)=>{
    if(err)
        reject(err)
    else
        resolve(data)
    })
})

promise
.then(data => {
    console.log('1st reading:', data.toString());
    return new Promise( (resolve, reject) =>{
        fs.readFile('./readme2.txt, (err, data)=>{
            if(err)
                reject(err)
            else
                resolve(data)
        });
    });
})

.then(data => {
    console.log('2st reading:', data.toString());
    return new Promise( (resolve, reject) =>{
        fs.readFile('./readme2.txt, (err, data)=>{
            if(err)
                reject(err)
            else
                resolve(data)
        });
    });
})
.then(data => console.log('3st reading:', data.toString()))
.catch(err => console.error(err.message);
.finally(() => console.log('end'));
  • 장점: 체이닝으로 결과를 연결할 수 있어 코드의 가독성이 올라간다, 에러 처리가 개선되어 .then() 과 .catch() 메서드를 사용하여 중앙 집중식으로 에러를 처리할 수 있다.
  • 단점: 여전히 .then()과 .catch()로 인해 가독성이 조금 떨어진다.

Async/Await 구문 (fs 모듈의 promises 이용)

const fs = require('fs);
const fsPromises = fs.promises;

console.log('start);
(async () => {
    try {
        let data = await fsPromises.readFile('./readme1.txt');
        console.log('1st reading:', data.toString());
        data = await fsPromises.readFile('./readme1.txt');
        console.log('2st reading:', data.toString());
        data = await fsPromises.readFile('./readme1.txt');
        console.log('3st reading:', data.toString());
    }
    catch(err){
        console.error(err.message);
    }
    finally{
        console.log('end');
    }
})();
  • 장점: try/catch 문을 사용하여 전통적인 에러 처리 방식과 유사하게 처리함으로서 가독성이 올라가게된다.
  • 단점: 오래된 브라우저에서는 지원하지 않을 가능성이 존재한다, 비동기 함수 내에서만 await 키워드를 사용이 가능하다

+fetch()

  • 웹 브라우저의 API로 웹 서버로 HTTP 요청을 보내는데 사용되며, promise 객체를 반환하는 방식으로 비동기 문제를 해결한다.
  • promise 객체가 resolve 응답 → then
  • promise 객체가 rejected 응답 → catch
fetch(url, options).then(response => {
    // 처리 로직
}).catch(error => {
    // 에러 처리 로직
});

예전 방식

function Vacation(destination, length){
  this.destination = destination
  this.length = length
}

Vacation.prototype.print = function(){
  console.log(this.destination + "는 "+
              this.length)
}

var trip = new Vacation("대구",4)
trip.print()

<출력 결과>

"대구는 4"

최신 방식

class Vacation{
  constructor(destination, length){
    this.destination = destination
    this.length = length
  }
  print(){
    console.log(`${this.destination}은(는)${this.length}일 걸립니다.`)
  }
}

var trip = new Vacation("강남",2)
trip.print()

<출력 결과>

"강남은(는)2일 걸립니다."

상속 기능

class Vacation{
  constructor(destination, length){
    this.destination = destination
    this.length = length
  }
  print(){
    console.log(`${this.destination}은(는)${this.length}일 걸립니다.`)
  }
}

var trip = new Vacation("강남",2)
trip.print()

class Expedition extends Vacation{
  constructor(destination, length, gear){
    super(destination,length)
    this.gear = gear
  }
  print(){
    super.print()
    console.log(`추가 ${this.gear}`)
  }
}

var upTrip = new Expedition("강남",2,10)
upTrip.print()

<출력 결과>

"강남은(는)2일 걸립니다."

"강남은(는)2일 걸립니다."

추가 10"

종류, 적용 우선순위

// 기본 바인딩
function showThis() {
  console.log(this); 
}

showThis(); // 출력은?
// window

// 암시적 바인딩
const obj = {
  name: "ChatGPT",
  speak: function() {
    console.log(this.name); 
  }
};

obj.speak(); // 출력은?
// ChatGPT

// 명시적 바인딩
function introduce(city) {
  console.log(`Hello, I am ${this.name} from ${city}`); 
}

const user = {
  name: "Alice"
};

introduce.call(user, "Wonderland"); // 출력은?
// Hello, I am Alice from Wonderland

// new 바인딩
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const bob = new Person("Bob", 25);
console.log(bob.name); // 출력은?
// Bob

// 화살표 함수 바인딩
const team = {
  members: ["Amy", "Bill"],
  teamName: "SuperTeam",
  show: function() {
    this.members.forEach(member => {
      console.log(`${member} is part of ${this.teamName}`);
    });
  }
};

team.show(); // 출력은?
// Amy is part of SuperTeam
// Bill is part of SuperTeam
  1. new 바인딩: 만약 함수가 new를 사용하여 생성자로 호출되면, this는 새로 생성된 객체를 참조한다.
  2. 명시적 바인딩: 함수가 .bind() , .call() 또는 .apply()로 호출되면, this는 이 메서드의 첫 번째 인수로 제공된 객체를 참조한다.
  3. 암시적 바인딩: 함수가 객체의 메서드로 호출되면, this는 해당 객체를 참조한다.
  4. 화살표 함수: 화살표 함수는 자신만의 this를 가지지 않는다. 대신, 화살표 함수는 생성 시점의 this 값을 가져온다. 화살표 함수의 this 바인딩은 기본적으로 선언되었던 위치의 실행 컨텍스트에서의 this 값으로 설정된다. 즉 상위 블럭에 존재하는 this 를 가르키게 된다.
  5. 기본 바인딩: 위의 규칙 중 어느 것도 해당되지 않으면, this는 기본적으로 전역 객체(브라우저에서는 Window)를 참조한다. 그러나, strict 모드에서는 thisundefined로 설정된다.

 

(예시 1)

const gangwon = {
  resorts: ["용평","평창","강촌","강릉","홍천"],
  print: function(delay=1000) {
    console.log(this);       // gangwon
    setTimeout(function() {
      console.log(this);     // Window
      console.log(this.resorts.join(","))
    }, delay)  // 바인딩 하지 않으면 this = window
  }
}

gangwon.print()

gangwon 객체와 그 안의 print 메서드를 기준으로 this의 참조와 해당 바인딩

  1. console.log(this);
    • 이 코드는 print 함수 내부에서 실행되는데, 이 함수는 gangwon 객체의 메서드로 호출된다. 따라서 여기서 thisgangwon 객체를 참조하게된다.
    • 바인딩 방식: 암시적 바인딩. 함수가 객체의 메서드로 호출되었기 때문에, this는 해당 메서드를 포함하고 있는 객체, 즉 gangwon 객체를 참조하게된다.
  2. setTimeout 내부의 console.log(this);
    • setTimeout의 콜백 함수는 전역 컨텍스트에서 실행되므로, 여기서의 this는 전역 객체를 참조하게된다. 브라우저 환경에서는 전역 객체가 Window으로 설정된다.
    • 바인딩 방식: 기본 바인딩. 콜백 함수는 특정 객체에 바인딩되어 있지 않고, 일반 함수로 실행되므로 this는 기본적으로 전역 객체를 참조한다.
  3. console.log(this.resorts.join(","))
    • 이 코드도 setTimeout의 콜백 함수 내부에서 실행되므로, this는 전역 객체인 Window를 참조한다. 그러나 Window 객체에는 resorts 프로퍼티가 없기 때문에, 이 코드를 실행하면 TypeError가 발생하게 된다.
    • 바인딩 방식: 기본 바인딩. 이 콜백 함수도 기본적으로 전역 객체를 참조한다.

<출력 결과>

{resorts: Array(5), print: ƒ}print: ƒ (delay=1000)resorts: (5) ['용평', '평창', '강촌', '강릉', '홍천'][[Prototype]]: Object
{window: Window, self: Window, document: document, name: '', location: Location, …}Babel: {availablePlugins: {…}, availablePresets: {…}, version: '6.14.0', transform: ƒ, transformFromAst: ƒ, …}alert: ƒ alert()atob: ƒ atob()blur: ƒ blur()btoa: ƒ btoa()caches: CacheStorage {}cancelAnimationFrame: ƒ cancelAnimationFrame()cancelIdleCallback: ƒ cancelIdleCallback()captureEvents: ƒ captureEvents()chrome: {loadTimes: ƒ, csi: ƒ}clearInterval: ƒ clearInterval()clearTimeout: ƒ clearTimeout()clientInformation: Navigator {vendorSub: '', productSub: '20030107', vendor: 'Google Inc.', maxTouchPoints: 0, scheduling: Scheduling, …}close: ƒ close()closed: falseconfirm: ƒ confirm()cookieStore: CookieStore {onchange: null}createImageBitmap: ƒ createImageBitmap()credentialless: falsecrossOriginIsolated: falsecrypto: Crypto {subtle: SubtleCrypto}customElements: CustomElementRegistry {}devicePixelRatio: 2document: documentdocumentPictureInPicture: DocumentPictureInPicture {window: null, onenter: null}external: External {}fence: nullfetch: ƒ fetch()find: ƒ find()focus: ƒ focus()frameElement: nullframes: Window {window: Window, self: Window, document: document, name: '', location: Location, …}getComputedStyle: ƒ getComputedStyle()getScreenDetails: ƒ getScreenDetails()getSelection: ƒ getSelection()history: History {length: 1, scrollRestoration: 'auto', state: null}indexedDB: IDBFactory {}innerHeight: 827innerWidth: 204isSecureContext: truelaunchQueue: LaunchQueue {}length: 0localStorage: Storage {length: 0}location: Location {ancestorOrigins: DOMStringList, href: 'file:///Users/imsuhan/Desktop/3%E1%84%92%E1%85%A1%…%E1%85%AE/03-arrow-functions/07-arrows-test1.html', origin: 'file://', protocol: 'file:', host: '', …}locationbar: BarProp {visible: true}matchMedia: ƒ matchMedia()menubar: BarProp {visible: true}moveBy: ƒ moveBy()moveTo: ƒ moveTo()name: ""navigation: Navigation {currentEntry: NavigationHistoryEntry, transition: null, canGoBack: false, canGoForward: false, onnavigate: null, …}navigator: Navigator {vendorSub: '', productSub: '20030107', vendor: 'Google Inc.', maxTouchPoints: 0, scheduling: Scheduling, …}onabort: nullonafterprint: nullonanimationend: nullonanimationiteration: nullonanimationstart: nullonappinstalled: nullonauxclick: nullonbeforeinput: nullonbeforeinstallprompt: nullonbeforematch: nullonbeforeprint: nullonbeforetoggle: nullonbeforeunload: nullonbeforexrselect: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontentvisibilityautostatechange: nulloncontextlost: nulloncontextmenu: nulloncontextrestored: nulloncuechange: nullondblclick: nullondevicemotion: nullondeviceorientation: nullondeviceorientationabsolute: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nullonformdata: nullongotpointercapture: nullonhashchange: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonlanguagechange: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonlostpointercapture: nullonmessage: nullonmessageerror: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonoffline: nullononline: nullonpagehide: nullonpageshow: nullonpause: nullonplay: nullonplaying: nullonpointercancel: nullonpointerdown: nullonpointerenter: nullonpointerleave: nullonpointermove: nullonpointerout: nullonpointerover: nullonpointerrawupdate: nullonpointerup: nullonpopstate: nullonprogress: nullonratechange: nullonrejectionhandled: nullonreset: nullonresize: nullonscroll: nullonscrollend: nullonsearch: nullonsecuritypolicyviolation: nullonseeked: nullonseeking: nullonselect: nullonselectionchange: nullonselectstart: nullonslotchange: nullonstalled: nullonstorage: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullontransitioncancel: nullontransitionend: nullontransitionrun: nullontransitionstart: nullonunhandledrejection: nullonunload: nullonvolumechange: nullonwaiting: nullonwebkitanimationend: nullonwebkitanimationiteration: nullonwebkitanimationstart: nullonwebkittransitionend: nullonwheel: nullopen: ƒ open()openDatabase: ƒ openDatabase()opener: nullorigin: "null"originAgentCluster: falseouterHeight: 944outerWidth: 942pageXOffset: 0pageYOffset: 0parent: Window {window: Window, self: Window, document: document, name: '', location: Location, …}performance: Performance {timeOrigin: 1693643973198.9, onresourcetimingbufferfull: null, timing: PerformanceTiming, navigation: PerformanceNavigation, memory: MemoryInfo, …}personalbar: BarProp {visible: true}postMessage: ƒ postMessage()print: ƒ print()prompt: ƒ prompt()queryLocalFonts: ƒ queryLocalFonts()queueMicrotask: ƒ queueMicrotask()releaseEvents: ƒ releaseEvents()reportError: ƒ reportError()requestAnimationFrame: ƒ requestAnimationFrame()requestIdleCallback: ƒ requestIdleCallback()resizeBy: ƒ resizeBy()resizeTo: ƒ resizeTo()scheduler: Scheduler {}screen: Screen {availWidth: 1512, availHeight: 944, width: 1512, height: 982, colorDepth: 30, …}screenLeft: 356screenTop: 38screenX: 356screenY: 38scroll: ƒ scroll()scrollBy: ƒ scrollBy()scrollTo: ƒ scrollTo()scrollX: 0scrollY: 0scrollbars: BarProp {visible: true}self: Window {window: Window, self: Window, document: document, name: '', location: Location, …}sessionStorage: Storage {length: 0}setInterval: ƒ setInterval()setTimeout: ƒ setTimeout()sharedStorage: SharedStorage {worklet: SharedStorageWorklet}showDirectoryPicker: ƒ showDirectoryPicker()showOpenFilePicker: ƒ showOpenFilePicker()showSaveFilePicker: ƒ showSaveFilePicker()speechSynthesis: SpeechSynthesis {pending: false, speaking: false, paused: false, onvoiceschanged: null}status: ""statusbar: BarProp {visible: true}stop: ƒ stop()structuredClone: ƒ structuredClone()styleMedia: StyleMedia {type: 'screen'}toolbar: BarProp {visible: true}top: Window {window: Window, self: Window, document: document, name: '', location: Location, …}trustedTypes: TrustedTypePolicyFactory {emptyHTML: emptyHTML "", emptyScript: emptyScript "", defaultPolicy: null}visualViewport: VisualViewport {offsetLeft: 0, offsetTop: 0, pageLeft: 0, pageTop: 0, width: 204, …}webkitCancelAnimationFrame: ƒ webkitCancelAnimationFrame()webkitRequestAnimationFrame: ƒ webkitRequestAnimationFrame()webkitRequestFileSystem: ƒ webkitRequestFileSystem()webkitResolveLocalFileSystemURL: ƒ webkitResolveLocalFileSystemURL()window: Window {window: Window, self: Window, document: document, name: '', location: Location, …}__core-js_shared__: {keys: {…}, wks: {…}, symbol-registry: {…}, symbols: {…}, op-symbols: {…}}Infinity: InfinityAbortController: ƒ AbortController()AbortSignal: ƒ AbortSignal()AbsoluteOrientationSensor: ƒ AbsoluteOrientationSensor()AbstractRange: ƒ AbstractRange()Accelerometer: ƒ Accelerometer()AggregateError: ƒ AggregateError()AnalyserNode: ƒ AnalyserNode()Animation: ƒ Animation()AnimationEffect: ƒ AnimationEffect()AnimationEvent: ƒ AnimationEvent()AnimationPlaybackEvent: ƒ AnimationPlaybackEvent()AnimationTimeline: ƒ AnimationTimeline()Array: ƒ Array()ArrayBuffer: ƒ ArrayBuffer()Atomics: Atomics {load: ƒ, store: ƒ, add: ƒ, sub: ƒ, and: ƒ, …}Attr: ƒ Attr()Audio: ƒ Audio()AudioBuffer: ƒ AudioBuffer()AudioBufferSourceNode: ƒ AudioBufferSourceNode()AudioContext: ƒ AudioContext()AudioData: ƒ AudioData()AudioDecoder: ƒ AudioDecoder()AudioDestinationNode: ƒ AudioDestinationNode()AudioEncoder: ƒ AudioEncoder()AudioListener: ƒ AudioListener()AudioNode: ƒ AudioNode()AudioParam: ƒ AudioParam()AudioParamMap: ƒ AudioParamMap()AudioProcessingEvent: ƒ AudioProcessingEvent()AudioScheduledSourceNode: ƒ AudioScheduledSourceNode()AudioSinkInfo: ƒ AudioSinkInfo()AudioWorklet: ƒ AudioWorklet()AudioWorkletNode: ƒ AudioWorkletNode()AuthenticatorAssertionResponse: ƒ AuthenticatorAssertionResponse()AuthenticatorAttestationResponse: ƒ AuthenticatorAttestationResponse()AuthenticatorResponse: ƒ AuthenticatorResponse()BackgroundFetchManager: ƒ BackgroundFetchManager()BackgroundFetchRecord: ƒ BackgroundFetchRecord()BackgroundFetchRegistration: ƒ BackgroundFetchRegistration()BarProp: ƒ BarProp()BarcodeDetector: ƒ BarcodeDetector()BaseAudioContext: ƒ BaseAudioContext()BatteryManager: ƒ BatteryManager()BeforeInstallPromptEvent: ƒ BeforeInstallPromptEvent()BeforeUnloadEvent: ƒ BeforeUnloadEvent()BigInt: ƒ BigInt()BigInt64Array: ƒ BigInt64Array()BigUint64Array: ƒ BigUint64Array()BiquadFilterNode: ƒ BiquadFilterNode()Blob: ƒ Blob()BlobEvent: ƒ BlobEvent()Bluetooth: ƒ Bluetooth()BluetoothCharacteristicProperties: ƒ BluetoothCharacteristicProperties()BluetoothDevice: ƒ BluetoothDevice()BluetoothRemoteGATTCharacteristic: ƒ BluetoothRemoteGATTCharacteristic()BluetoothRemoteGATTDescriptor: ƒ BluetoothRemoteGATTDescriptor()BluetoothRemoteGATTServer: ƒ BluetoothRemoteGATTServer()BluetoothRemoteGATTService: ƒ BluetoothRemoteGATTService()BluetoothUUID: ƒ BluetoothUUID()Boolean: ƒ Boolean()BroadcastChannel: ƒ BroadcastChannel()BrowserCaptureMediaStreamTrack: ƒ BrowserCaptureMediaStreamTrack()ByteLengthQueuingStrategy: ƒ ByteLengthQueuingStrategy()CDATASection: ƒ CDATASection()CSS: CSS {Hz: ƒ, Q: ƒ, ch: ƒ, cm: ƒ, cqb: ƒ, …}CSSAnimation: ƒ CSSAnimation()CSSConditionRule: ƒ CSSConditionRule()CSSContainerRule: ƒ CSSContainerRule()CSSCounterStyleRule: ƒ CSSCounterStyleRule()CSSFontFaceRule: ƒ CSSFontFaceRule()CSSFontPaletteValuesRule: ƒ CSSFontPaletteValuesRule()CSSGroupingRule: ƒ CSSGroupingRule()CSSImageValue: ƒ CSSImageValue()CSSImportRule: ƒ CSSImportRule()CSSKeyframeRule: ƒ CSSKeyframeRule()CSSKeyframesRule: ƒ CSSKeyframesRule()CSSKeywordValue: ƒ CSSKeywordValue()CSSLayerBlockRule: ƒ CSSLayerBlockRule()CSSLayerStatementRule: ƒ CSSLayerStatementRule()CSSMathClamp: ƒ CSSMathClamp()CSSMathInvert: ƒ CSSMathInvert()CSSMathMax: ƒ CSSMathMax()CSSMathMin: ƒ CSSMathMin()CSSMathNegate: ƒ CSSMathNegate()CSSMathProduct: ƒ CSSMathProduct()CSSMathSum: ƒ CSSMathSum()CSSMathValue: ƒ CSSMathValue()CSSMatrixComponent: ƒ CSSMatrixComponent()CSSMediaRule: ƒ CSSMediaRule()CSSNamespaceRule: ƒ CSSNamespaceRule()CSSNumericArray: ƒ CSSNumericArray()CSSNumericValue: ƒ CSSNumericValue()CSSPageRule: ƒ CSSPageRule()CSSPerspective: ƒ CSSPerspective()CSSPositionValue: ƒ CSSPositionValue()CSSPropertyRule: ƒ CSSPropertyRule()CSSRotate: ƒ CSSRotate()CSSRule: ƒ CSSRule()CSSRuleList: ƒ CSSRuleList()CSSScale: ƒ CSSScale()CSSSkew: ƒ CSSSkew()CSSSkewX: ƒ CSSSkewX()CSSSkewY: ƒ CSSSkewY()CSSStyleDeclaration: ƒ CSSStyleDeclaration()CSSStyleRule: ƒ CSSStyleRule()CSSStyleSheet: ƒ CSSStyleSheet()CSSStyleValue: ƒ CSSStyleValue()CSSSupportsRule: ƒ CSSSupportsRule()CSSTransformComponent: ƒ CSSTransformComponent()CSSTransformValue: ƒ CSSTransformValue()CSSTransition: ƒ CSSTransition()CSSTranslate: ƒ CSSTranslate()CSSUnitValue: ƒ CSSUnitValue()CSSUnparsedValue: ƒ CSSUnparsedValue()CSSVariableReferenceValue: ƒ CSSVariableReferenceValue()Cache: ƒ Cache()CacheStorage: ƒ CacheStorage()CanvasCaptureMediaStreamTrack: ƒ CanvasCaptureMediaStreamTrack()CanvasGradient: ƒ CanvasGradient()CanvasPattern: ƒ CanvasPattern()CanvasRenderingContext2D: ƒ CanvasRenderingContext2D()CaptureController: ƒ CaptureController()ChannelMergerNode: ƒ ChannelMergerNode()ChannelSplitterNode: ƒ ChannelSplitterNode()CharacterData: ƒ CharacterData()Clipboard: ƒ Clipboard()ClipboardEvent: ƒ ClipboardEvent()ClipboardItem: ƒ ClipboardItem()CloseEvent: ƒ CloseEvent()Comment: ƒ Comment()CompositionEvent: ƒ CompositionEvent()CompressionStream: ƒ CompressionStream()ConstantSourceNode: ƒ ConstantSourceNode()ContentVisibilityAutoStateChangeEvent: ƒ ContentVisibilityAutoStateChangeEvent()ConvolverNode: ƒ ConvolverNode()CookieChangeEvent: ƒ CookieChangeEvent()CookieStore: ƒ CookieStore()CookieStoreManager: ƒ CookieStoreManager()CountQueuingStrategy: ƒ CountQueuingStrategy()Credential: ƒ Credential()CredentialsContainer: ƒ CredentialsContainer()CropTarget: ƒ CropTarget()Crypto: ƒ Crypto()CryptoKey: ƒ CryptoKey()CustomElementRegistry: ƒ CustomElementRegistry()CustomEvent: ƒ CustomEvent()CustomStateSet: ƒ CustomStateSet()DOMError: ƒ DOMError()DOMException: ƒ DOMException()DOMImplementation: ƒ DOMImplementation()DOMMatrix: ƒ DOMMatrix()DOMMatrixReadOnly: ƒ DOMMatrixReadOnly()DOMParser: ƒ DOMParser()DOMPoint: ƒ DOMPoint()DOMPointReadOnly: ƒ DOMPointReadOnly()DOMQuad: ƒ DOMQuad()DOMRect: ƒ DOMRect()DOMRectList: ƒ DOMRectList()DOMRectReadOnly: ƒ DOMRectReadOnly()DOMStringList: ƒ DOMStringList()DOMStringMap: ƒ DOMStringMap()DOMTokenList: ƒ DOMTokenList()DataTransfer: ƒ DataTransfer()DataTransferItem: ƒ DataTransferItem()DataTransferItemList: ƒ DataTransferItemList()DataView: ƒ DataView()Date: ƒ Date()DecompressionStream: ƒ DecompressionStream()DelayNode: ƒ DelayNode()DelegatedInkTrailPresenter: ƒ DelegatedInkTrailPresenter()DeviceMotionEvent: ƒ DeviceMotionEvent()DeviceMotionEventAcceleration: ƒ DeviceMotionEventAcceleration()DeviceMotionEventRotationRate: ƒ DeviceMotionEventRotationRate()DeviceOrientationEvent: ƒ DeviceOrientationEvent()Document: ƒ Document()DocumentFragment: ƒ DocumentFragment()DocumentPictureInPicture: ƒ DocumentPictureInPicture()DocumentPictureInPictureEvent: ƒ DocumentPictureInPictureEvent()DocumentTimeline: ƒ DocumentTimeline()DocumentType: ƒ DocumentType()DragEvent: ƒ DragEvent()DynamicsCompressorNode: ƒ DynamicsCompressorNode()Element: ƒ Element()ElementInternals: ƒ ElementInternals()EncodedAudioChunk: ƒ EncodedAudioChunk()EncodedVideoChunk: ƒ EncodedVideoChunk()Error: ƒ Error()ErrorEvent: ƒ ErrorEvent()EvalError: ƒ EvalError()Event: ƒ Event()EventCounts: ƒ EventCounts()EventSource: ƒ EventSource()EventTarget: ƒ EventTarget()External: ƒ External()EyeDropper: ƒ EyeDropper()FeaturePolicy: ƒ FeaturePolicy()FederatedCredential: ƒ FederatedCredential()Fence: ƒ Fence()FencedFrameConfig: ƒ FencedFrameConfig()File: ƒ File()FileList: ƒ FileList()FileReader: ƒ FileReader()FileSystemDirectoryHandle: ƒ FileSystemDirectoryHandle()FileSystemFileHandle: ƒ FileSystemFileHandle()FileSystemHandle: ƒ FileSystemHandle()FileSystemWritableFileStream: ƒ FileSystemWritableFileStream()FinalizationRegistry: ƒ FinalizationRegistry()Float32Array: ƒ Float32Array()Float64Array: ƒ Float64Array()FocusEvent: ƒ FocusEvent()FontData: ƒ FontData()FontFace: ƒ FontFace()FontFaceSetLoadEvent: ƒ FontFaceSetLoadEvent()FormData: ƒ FormData()FormDataEvent: ƒ FormDataEvent()FragmentDirective: ƒ FragmentDirective()Function: ƒ Function()GPU: ƒ GPU()GPUAdapter: ƒ GPUAdapter()GPUAdapterInfo: ƒ GPUAdapterInfo()GPUBindGroup: ƒ GPUBindGroup()GPUBindGroupLayout: ƒ GPUBindGroupLayout()GPUBuffer: ƒ GPUBuffer()GPUBufferUsage: GPUBufferUsage {MAP_READ: 1, MAP_WRITE: 2, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, …}GPUCanvasContext: ƒ GPUCanvasContext()GPUColorWrite: GPUColorWrite {RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15, …}GPUCommandBuffer: ƒ GPUCommandBuffer()GPUCommandEncoder: ƒ GPUCommandEncoder()GPUCompilationInfo: ƒ GPUCompilationInfo()GPUCompilationMessage: ƒ GPUCompilationMessage()GPUComputePassEncoder: ƒ GPUComputePassEncoder()GPUComputePipeline: ƒ GPUComputePipeline()GPUDevice: ƒ GPUDevice()GPUDeviceLostInfo: ƒ GPUDeviceLostInfo()GPUError: ƒ GPUError()GPUExternalTexture: ƒ GPUExternalTexture()GPUInternalError: ƒ GPUInternalError()GPUMapMode: GPUMapMode {READ: 1, WRITE: 2, Symbol(Symbol.toStringTag): 'GPUMapMode'}GPUOutOfMemoryError: ƒ GPUOutOfMemoryError()GPUPipelineError: ƒ GPUPipelineError()GPUPipelineLayout: ƒ GPUPipelineLayout()GPUQuerySet: ƒ GPUQuerySet()GPUQueue: ƒ GPUQueue()GPURenderBundle: ƒ GPURenderBundle()GPURenderBundleEncoder: ƒ GPURenderBundleEncoder()GPURenderPassEncoder: ƒ GPURenderPassEncoder()GPURenderPipeline: ƒ GPURenderPipeline()GPUSampler: ƒ GPUSampler()GPUShaderModule: ƒ GPUShaderModule()GPUShaderStage: GPUShaderStage {VERTEX: 1, FRAGMENT: 2, COMPUTE: 4, Symbol(Symbol.toStringTag): 'GPUShaderStage'}GPUSupportedFeatures: ƒ GPUSupportedFeatures()GPUSupportedLimits: ƒ GPUSupportedLimits()GPUTexture: ƒ GPUTexture()GPUTextureUsage: GPUTextureUsage {COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16, …}GPUTextureView: ƒ GPUTextureView()GPUUncapturedErrorEvent: ƒ GPUUncapturedErrorEvent()GPUValidationError: ƒ GPUValidationError()GainNode: ƒ GainNode()Gamepad: ƒ Gamepad()GamepadButton: ƒ GamepadButton()GamepadEvent: ƒ GamepadEvent()GamepadHapticActuator: ƒ GamepadHapticActuator()Geolocation: ƒ Geolocation()GeolocationCoordinates: ƒ GeolocationCoordinates()GeolocationPosition: ƒ GeolocationPosition()GeolocationPositionError: ƒ GeolocationPositionError()GravitySensor: ƒ GravitySensor()Gyroscope: ƒ Gyroscope()HID: ƒ HID()HIDConnectionEvent: ƒ HIDConnectionEvent()HIDDevice: ƒ HIDDevice()HIDInputReportEvent: ƒ HIDInputReportEvent()HTMLAllCollection: ƒ HTMLAllCollection()HTMLAnchorElement: ƒ HTMLAnchorElement()HTMLAreaElement: ƒ HTMLAreaElement()HTMLAudioElement: ƒ HTMLAudioElement()HTMLBRElement: ƒ HTMLBRElement()HTMLBaseElement: ƒ HTMLBaseElement()HTMLBodyElement: ƒ HTMLBodyElement()HTMLButtonElement: ƒ HTMLButtonElement()HTMLCanvasElement: ƒ HTMLCanvasElement()HTMLCollection: ƒ HTMLCollection()HTMLDListElement: ƒ HTMLDListElement()HTMLDataElement: ƒ HTMLDataElement()HTMLDataListElement: ƒ HTMLDataListElement()HTMLDetailsElement: ƒ HTMLDetailsElement()HTMLDialogElement: ƒ HTMLDialogElement()HTMLDirectoryElement: ƒ HTMLDirectoryElement()HTMLDivElement: ƒ HTMLDivElement()HTMLDocument: ƒ HTMLDocument()HTMLElement: ƒ HTMLElement()HTMLEmbedElement: ƒ HTMLEmbedElement()HTMLFencedFrameElement: ƒ HTMLFencedFrameElement()HTMLFieldSetElement: ƒ HTMLFieldSetElement()HTMLFontElement: ƒ HTMLFontElement()HTMLFormControlsCollection: ƒ HTMLFormControlsCollection()HTMLFormElement: ƒ HTMLFormElement()HTMLFrameElement: ƒ HTMLFrameElement()HTMLFrameSetElement: ƒ HTMLFrameSetElement()HTMLHRElement: ƒ HTMLHRElement()HTMLHeadElement: ƒ HTMLHeadElement()HTMLHeadingElement: ƒ HTMLHeadingElement()HTMLHtmlElement: ƒ HTMLHtmlElement()HTMLIFrameElement: ƒ HTMLIFrameElement()HTMLImageElement: ƒ HTMLImageElement()HTMLInputElement: ƒ HTMLInputElement()HTMLLIElement: ƒ HTMLLIElement()HTMLLabelElement: ƒ HTMLLabelElement()HTMLLegendElement: ƒ HTMLLegendElement()HTMLLinkElement: ƒ HTMLLinkElement()HTMLMapElement: ƒ HTMLMapElement()HTMLMarqueeElement: ƒ HTMLMarqueeElement()HTMLMediaElement: ƒ HTMLMediaElement()HTMLMenuElement: ƒ HTMLMenuElement()HTMLMetaElement: ƒ HTMLMetaElement()HTMLMeterElement: ƒ HTMLMeterElement()HTMLModElement: ƒ HTMLModElement()HTMLOListElement: ƒ HTMLOListElement()HTMLObjectElement: ƒ HTMLObjectElement()HTMLOptGroupElement: ƒ HTMLOptGroupElement()HTMLOptionElement: ƒ HTMLOptionElement()HTMLOptionsCollection: ƒ HTMLOptionsCollection()HTMLOutputElement: ƒ HTMLOutputElement()HTMLParagraphElement: ƒ HTMLParagraphElement()HTMLParamElement: ƒ HTMLParamElement()HTMLPictureElement: ƒ HTMLPictureElement()HTMLPreElement: ƒ HTMLPreElement()HTMLProgressElement: ƒ HTMLProgressElement()HTMLQuoteElement: ƒ HTMLQuoteElement()HTMLScriptElement: ƒ HTMLScriptElement()HTMLSelectElement: ƒ HTMLSelectElement()HTMLSlotElement: ƒ HTMLSlotElement()HTMLSourceElement: ƒ HTMLSourceElement()HTMLSpanElement: ƒ HTMLSpanElement()HTMLStyleElement: ƒ HTMLStyleElement()HTMLTableCaptionElement: ƒ HTMLTableCaptionElement()HTMLTableCellElement: ƒ HTMLTableCellElement()HTMLTableColElement: ƒ HTMLTableColElement()HTMLTableElement: ƒ HTMLTableElement()HTMLTableRowElement: ƒ HTMLTableRowElement()HTMLTableSectionElement: ƒ HTMLTableSectionElement()HTMLTemplateElement: ƒ HTMLTemplateElement()HTMLTextAreaElement: ƒ HTMLTextAreaElement()HTMLTimeElement: ƒ HTMLTimeElement()HTMLTitleElement: ƒ HTMLTitleElement()HTMLTrackElement: ƒ HTMLTrackElement()HTMLUListElement: ƒ HTMLUListElement()HTMLUnknownElement: ƒ HTMLUnknownElement()HTMLVideoElement: ƒ HTMLVideoElement()HashChangeEvent: ƒ HashChangeEvent()Headers: ƒ Headers()Highlight: ƒ Highlight()HighlightRegistry: ƒ HighlightRegistry()History: ƒ History()IDBCursor: ƒ IDBCursor()IDBCursorWithValue: ƒ IDBCursorWithValue()IDBDatabase: ƒ IDBDatabase()IDBFactory: ƒ IDBFactory()IDBIndex: ƒ IDBIndex()IDBKeyRange: ƒ IDBKeyRange()IDBObjectStore: ƒ IDBObjectStore()IDBOpenDBRequest: ƒ IDBOpenDBRequest()IDBRequest: ƒ IDBRequest()IDBTransaction: ƒ IDBTransaction()IDBVersionChangeEvent: ƒ IDBVersionChangeEvent()IIRFilterNode: ƒ IIRFilterNode()IdentityCredential: ƒ IdentityCredential()IdentityProvider: ƒ IdentityProvider()IdleDeadline: ƒ IdleDeadline()IdleDetector: ƒ IdleDetector()Image: ƒ Image()ImageBitmap: ƒ ImageBitmap()ImageBitmapRenderingContext: ƒ ImageBitmapRenderingContext()ImageCapture: ƒ ImageCapture()ImageData: ƒ ImageData()ImageDecoder: ƒ ImageDecoder()ImageTrack: ƒ ImageTrack()ImageTrackList: ƒ ImageTrackList()Ink: ƒ Ink()InputDeviceCapabilities: ƒ InputDeviceCapabilities()InputDeviceInfo: ƒ InputDeviceInfo()InputEvent: ƒ InputEvent()Int8Array: ƒ Int8Array()Int16Array: ƒ Int16Array()Int32Array: ƒ Int32Array()IntersectionObserver: ƒ IntersectionObserver()IntersectionObserverEntry: ƒ IntersectionObserverEntry()Intl: Intl {getCanonicalLocales: ƒ, supportedValuesOf: ƒ, DateTimeFormat: ƒ, NumberFormat: ƒ, Collator: ƒ, …}JSON: JSON {Symbol(Symbol.toStringTag): 'JSON', parse: ƒ, stringify: ƒ, rawJSON: ƒ, isRawJSON: ƒ}Keyboard: ƒ Keyboard()KeyboardEvent: ƒ KeyboardEvent()KeyboardLayoutMap: ƒ KeyboardLayoutMap()KeyframeEffect: ƒ KeyframeEffect()LargestContentfulPaint: ƒ LargestContentfulPaint()LaunchParams: ƒ LaunchParams()LaunchQueue: ƒ LaunchQueue()LayoutShift: ƒ LayoutShift()LayoutShiftAttribution: ƒ LayoutShiftAttribution()LinearAccelerationSensor: ƒ LinearAccelerationSensor()Location: ƒ Location()Lock: ƒ Lock()LockManager: ƒ LockManager()MIDIAccess: ƒ MIDIAccess()MIDIConnectionEvent: ƒ MIDIConnectionEvent()MIDIInput: ƒ MIDIInput()MIDIInputMap: ƒ MIDIInputMap()MIDIMessageEvent: ƒ MIDIMessageEvent()MIDIOutput: ƒ MIDIOutput()MIDIOutputMap: ƒ MIDIOutputMap()MIDIPort: ƒ MIDIPort()Map: ƒ Map()Math: Math {abs: ƒ, acos: ƒ, acosh: ƒ, asin: ƒ, asinh: ƒ, …}MathMLElement: ƒ MathMLElement()MediaCapabilities: ƒ MediaCapabilities()MediaDeviceInfo: ƒ MediaDeviceInfo()MediaDevices: ƒ MediaDevices()MediaElementAudioSourceNode: ƒ MediaElementAudioSourceNode()MediaEncryptedEvent: ƒ MediaEncryptedEvent()MediaError: ƒ MediaError()MediaKeyMessageEvent: ƒ MediaKeyMessageEvent()MediaKeySession: ƒ MediaKeySession()MediaKeyStatusMap: ƒ MediaKeyStatusMap()MediaKeySystemAccess: ƒ MediaKeySystemAccess()MediaKeys: ƒ MediaKeys()MediaList: ƒ MediaList()MediaMetadata: ƒ MediaMetadata()MediaQueryList: ƒ MediaQueryList()MediaQueryListEvent: ƒ MediaQueryListEvent()MediaRecorder: ƒ MediaRecorder()MediaSession: ƒ MediaSession()MediaSource: ƒ MediaSource()MediaSourceHandle: ƒ MediaSourceHandle()MediaStream: ƒ MediaStream()MediaStreamAudioDestinationNode: ƒ MediaStreamAudioDestinationNode()MediaStreamAudioSourceNode: ƒ MediaStreamAudioSourceNode()MediaStreamEvent: ƒ MediaStreamEvent()MediaStreamTrack: ƒ MediaStreamTrack()MediaStreamTrackEvent: ƒ MediaStreamTrackEvent()MediaStreamTrackGenerator: ƒ MediaStreamTrackGenerator()MediaStreamTrackProcessor: ƒ MediaStreamTrackProcessor()MessageChannel: ƒ MessageChannel()MessageEvent: ƒ MessageEvent()MessagePort: ƒ MessagePort()MimeType: ƒ MimeType()MimeTypeArray: ƒ MimeTypeArray()MouseEvent: ƒ MouseEvent()MutationEvent: ƒ MutationEvent()MutationObserver: ƒ MutationObserver()MutationRecord: ƒ MutationRecord()NaN: NaNNamedNodeMap: ƒ NamedNodeMap()NavigateEvent: ƒ NavigateEvent()Navigation: ƒ Navigation()NavigationCurrentEntryChangeEvent: ƒ NavigationCurrentEntryChangeEvent()NavigationDestination: ƒ NavigationDestination()NavigationHistoryEntry: ƒ NavigationHistoryEntry()NavigationPreloadManager: ƒ NavigationPreloadManager()NavigationTransition: ƒ NavigationTransition()Navigator: ƒ Navigator()NavigatorManagedData: ƒ NavigatorManagedData()NavigatorUAData: ƒ NavigatorUAData()NetworkInformation: ƒ NetworkInformation()Node: ƒ Node()NodeFilter: ƒ NodeFilter()NodeIterator: ƒ NodeIterator()NodeList: ƒ NodeList()Notification: ƒ Notification()Number: ƒ Number()OTPCredential: ƒ OTPCredential()Object: ƒ Object()OfflineAudioCompletionEvent: ƒ OfflineAudioCompletionEvent()OfflineAudioContext: ƒ OfflineAudioContext()OffscreenCanvas: ƒ OffscreenCanvas()OffscreenCanvasRenderingContext2D: ƒ OffscreenCanvasRenderingContext2D()Option: ƒ Option()OrientationSensor: ƒ OrientationSensor()OscillatorNode: ƒ OscillatorNode()OverconstrainedError: ƒ OverconstrainedError()PageTransitionEvent: ƒ PageTransitionEvent()PannerNode: ƒ PannerNode()PasswordCredential: ƒ PasswordCredential()Path2D: ƒ Path2D()PaymentAddress: ƒ PaymentAddress()PaymentManager: ƒ PaymentManager()PaymentMethodChangeEvent: ƒ PaymentMethodChangeEvent()PaymentRequest: ƒ PaymentRequest()PaymentRequestUpdateEvent: ƒ PaymentRequestUpdateEvent()PaymentResponse: ƒ PaymentResponse()Performance: ƒ Performance()PerformanceElementTiming: ƒ PerformanceElementTiming()PerformanceEntry: ƒ PerformanceEntry()PerformanceEventTiming: ƒ PerformanceEventTiming()PerformanceLongTaskTiming: ƒ PerformanceLongTaskTiming()PerformanceMark: ƒ PerformanceMark()PerformanceMeasure: ƒ PerformanceMeasure()PerformanceNavigation: ƒ PerformanceNavigation()PerformanceNavigationTiming: ƒ PerformanceNavigationTiming()PerformanceObserver: ƒ PerformanceObserver()PerformanceObserverEntryList: ƒ PerformanceObserverEntryList()PerformancePaintTiming: ƒ PerformancePaintTiming()PerformanceResourceTiming: ƒ PerformanceResourceTiming()PerformanceServerTiming: ƒ PerformanceServerTiming()PerformanceTiming: ƒ PerformanceTiming()PeriodicSyncManager: ƒ PeriodicSyncManager()PeriodicWave: ƒ PeriodicWave()PermissionStatus: ƒ PermissionStatus()Permissions: ƒ Permissions()PictureInPictureEvent: ƒ PictureInPictureEvent()PictureInPictureWindow: ƒ PictureInPictureWindow()Plugin: ƒ Plugin()PluginArray: ƒ PluginArray()PointerEvent: ƒ PointerEvent()PopStateEvent: ƒ PopStateEvent()Presentation: ƒ Presentation()PresentationAvailability: ƒ PresentationAvailability()PresentationConnection: ƒ PresentationConnection()PresentationConnectionAvailableEvent: ƒ PresentationConnectionAvailableEvent()PresentationConnectionCloseEvent: ƒ PresentationConnectionCloseEvent()PresentationConnectionList: ƒ PresentationConnectionList()PresentationReceiver: ƒ PresentationReceiver()PresentationRequest: ƒ PresentationRequest()ProcessingInstruction: ƒ ProcessingInstruction()Profiler: ƒ Profiler()ProgressEvent: ƒ ProgressEvent()Promise: ƒ Promise()PromiseRejectionEvent: ƒ PromiseRejectionEvent()Proxy: ƒ Proxy()PublicKeyCredential: ƒ PublicKeyCredential()PushManager: ƒ PushManager()PushSubscription: ƒ PushSubscription()PushSubscriptionOptions: ƒ PushSubscriptionOptions()RTCCertificate: ƒ RTCCertificate()RTCDTMFSender: ƒ RTCDTMFSender()RTCDTMFToneChangeEvent: ƒ RTCDTMFToneChangeEvent()RTCDataChannel: ƒ RTCDataChannel()RTCDataChannelEvent: ƒ RTCDataChannelEvent()RTCDtlsTransport: ƒ RTCDtlsTransport()RTCEncodedAudioFrame: ƒ RTCEncodedAudioFrame()RTCEncodedVideoFrame: ƒ RTCEncodedVideoFrame()RTCError: ƒ RTCError()RTCErrorEvent: ƒ RTCErrorEvent()RTCIceCandidate: ƒ RTCIceCandidate()RTCIceTransport: ƒ RTCIceTransport()RTCPeerConnection: ƒ RTCPeerConnection()RTCPeerConnectionIceErrorEvent: ƒ RTCPeerConnectionIceErrorEvent()RTCPeerConnectionIceEvent: ƒ RTCPeerConnectionIceEvent()RTCRtpReceiver: ƒ RTCRtpReceiver()RTCRtpSender: ƒ RTCRtpSender()RTCRtpTransceiver: ƒ RTCRtpTransceiver()RTCSctpTransport: ƒ RTCSctpTransport()RTCSessionDescription: ƒ RTCSessionDescription()RTCStatsReport: ƒ RTCStatsReport()RTCTrackEvent: ƒ RTCTrackEvent()RadioNodeList: ƒ RadioNodeList()Range: ƒ Range()RangeError: ƒ RangeError()ReadableByteStreamController: ƒ ReadableByteStreamController()ReadableStream: ƒ ReadableStream()ReadableStreamBYOBReader: ƒ ReadableStreamBYOBReader()ReadableStreamBYOBRequest: ƒ ReadableStreamBYOBRequest()ReadableStreamDefaultController: ƒ ReadableStreamDefaultController()ReadableStreamDefaultReader: ƒ ReadableStreamDefaultReader()ReferenceError: ƒ ReferenceError()Reflect: Reflect {defineProperty: ƒ, deleteProperty: ƒ, apply: ƒ, construct: ƒ, get: ƒ, …}RegExp: ƒ RegExp()RelativeOrientationSensor: ƒ RelativeOrientationSensor()RemotePlayback: ƒ RemotePlayback()ReportingObserver: ƒ ReportingObserver()Request: ƒ Request()ResizeObserver: ƒ ResizeObserver()ResizeObserverEntry: ƒ ResizeObserverEntry()ResizeObserverSize: ƒ ResizeObserverSize()Response: ƒ Response()SVGAElement: ƒ SVGAElement()SVGAngle: ƒ SVGAngle()SVGAnimateElement: ƒ SVGAnimateElement()SVGAnimateMotionElement: ƒ SVGAnimateMotionElement()SVGAnimateTransformElement: ƒ SVGAnimateTransformElement()SVGAnimatedAngle: ƒ SVGAnimatedAngle()SVGAnimatedBoolean: ƒ SVGAnimatedBoolean()SVGAnimatedEnumeration: ƒ SVGAnimatedEnumeration()SVGAnimatedInteger: ƒ SVGAnimatedInteger()SVGAnimatedLength: ƒ SVGAnimatedLength()SVGAnimatedLengthList: ƒ SVGAnimatedLengthList()SVGAnimatedNumber: ƒ SVGAnimatedNumber()SVGAnimatedNumberList: ƒ SVGAnimatedNumberList()SVGAnimatedPreserveAspectRatio: ƒ SVGAnimatedPreserveAspectRatio()SVGAnimatedRect: ƒ SVGAnimatedRect()SVGAnimatedString: ƒ SVGAnimatedString()SVGAnimatedTransformList: ƒ SVGAnimatedTransformList()SVGAnimationElement: ƒ SVGAnimationElement()SVGCircleElement: ƒ SVGCircleElement()SVGClipPathElement: ƒ SVGClipPathElement()SVGComponentTransferFunctionElement: ƒ SVGComponentTransferFunctionElement()SVGDefsElement: ƒ SVGDefsElement()SVGDescElement: ƒ SVGDescElement()SVGElement: ƒ SVGElement()SVGEllipseElement: ƒ SVGEllipseElement()SVGFEBlendElement: ƒ SVGFEBlendElement()SVGFEColorMatrixElement: ƒ SVGFEColorMatrixElement()SVGFEComponentTransferElement: ƒ SVGFEComponentTransferElement()SVGFECompositeElement: ƒ SVGFECompositeElement()SVGFEConvolveMatrixElement: ƒ SVGFEConvolveMatrixElement()SVGFEDiffuseLightingElement: ƒ SVGFEDiffuseLightingElement()SVGFEDisplacementMapElement: ƒ SVGFEDisplacementMapElement()SVGFEDistantLightElement: ƒ SVGFEDistantLightElement()SVGFEDropShadowElement: ƒ SVGFEDropShadowElement()SVGFEFloodElement: ƒ SVGFEFloodElement()SVGFEFuncAElement: ƒ SVGFEFuncAElement()SVGFEFuncBElement: ƒ SVGFEFuncBElement()SVGFEFuncGElement: ƒ SVGFEFuncGElement()SVGFEFuncRElement: ƒ SVGFEFuncRElement()SVGFEGaussianBlurElement: ƒ SVGFEGaussianBlurElement()SVGFEImageElement: ƒ SVGFEImageElement()SVGFEMergeElement: ƒ SVGFEMergeElement()SVGFEMergeNodeElement: ƒ SVGFEMergeNodeElement()SVGFEMorphologyElement: ƒ SVGFEMorphologyElement()SVGFEOffsetElement: ƒ SVGFEOffsetElement()SVGFEPointLightElement: ƒ SVGFEPointLightElement()SVGFESpecularLightingElement: ƒ SVGFESpecularLightingElement()SVGFESpotLightElement: ƒ SVGFESpotLightElement()SVGFETileElement: ƒ SVGFETileElement()SVGFETurbulenceElement: ƒ SVGFETurbulenceElement()SVGFilterElement: ƒ SVGFilterElement()SVGForeignObjectElement: ƒ SVGForeignObjectElement()SVGGElement: ƒ SVGGElement()SVGGeometryElement: ƒ SVGGeometryElement()SVGGradientElement: ƒ SVGGradientElement()SVGGraphicsElement: ƒ SVGGraphicsElement()SVGImageElement: ƒ SVGImageElement()SVGLength: ƒ SVGLength()SVGLengthList: ƒ SVGLengthList()SVGLineElement: ƒ SVGLineElement()SVGLinearGradientElement: ƒ SVGLinearGradientElement()SVGMPathElement: ƒ SVGMPathElement()SVGMarkerElement: ƒ SVGMarkerElement()SVGMaskElement: ƒ SVGMaskElement()SVGMatrix: ƒ SVGMatrix()SVGMetadataElement: ƒ SVGMetadataElement()SVGNumber: ƒ SVGNumber()SVGNumberList: ƒ SVGNumberList()SVGPathElement: ƒ SVGPathElement()SVGPatternElement: ƒ SVGPatternElement()SVGPoint: ƒ SVGPoint()SVGPointList: ƒ SVGPointList()SVGPolygonElement: ƒ SVGPolygonElement()SVGPolylineElement: ƒ SVGPolylineElement()SVGPreserveAspectRatio: ƒ SVGPreserveAspectRatio()SVGRadialGradientElement: ƒ SVGRadialGradientElement()SVGRect: ƒ SVGRect()SVGRectElement: ƒ SVGRectElement()SVGSVGElement: ƒ SVGSVGElement()SVGScriptElement: ƒ SVGScriptElement()SVGSetElement: ƒ SVGSetElement()SVGStopElement: ƒ SVGStopElement()SVGStringList: ƒ SVGStringList()SVGStyleElement: ƒ SVGStyleElement()SVGSwitchElement: ƒ SVGSwitchElement()SVGSymbolElement: ƒ SVGSymbolElement()SVGTSpanElement: ƒ SVGTSpanElement()SVGTextContentElement: ƒ SVGTextContentElement()SVGTextElement: ƒ SVGTextElement()SVGTextPathElement: ƒ SVGTextPathElement()SVGTextPositioningElement: ƒ SVGTextPositioningElement()SVGTitleElement: ƒ SVGTitleElement()SVGTransform: ƒ SVGTransform()SVGTransformList: ƒ SVGTransformList()SVGUnitTypes: ƒ SVGUnitTypes()SVGUseElement: ƒ SVGUseElement()SVGViewElement: ƒ SVGViewElement()Sanitizer: ƒ Sanitizer()Scheduler: ƒ Scheduler()Scheduling: ƒ Scheduling()Screen: ƒ Screen()ScreenDetailed: ƒ ScreenDetailed()ScreenDetails: ƒ ScreenDetails()ScreenOrientation: ƒ ScreenOrientation()ScriptProcessorNode: ƒ ScriptProcessorNode()ScrollTimeline: ƒ ScrollTimeline()SecurityPolicyViolationEvent: ƒ SecurityPolicyViolationEvent()Selection: ƒ Selection()Sensor: ƒ Sensor()SensorErrorEvent: ƒ SensorErrorEvent()Serial: ƒ Serial()SerialPort: ƒ SerialPort()ServiceWorker: ƒ ServiceWorker()ServiceWorkerContainer: ƒ ServiceWorkerContainer()ServiceWorkerRegistration: ƒ ServiceWorkerRegistration()Set: ƒ Set()ShadowRoot: ƒ ShadowRoot()SharedStorage: ƒ SharedStorage()SharedStorageWorklet: ƒ SharedStorageWorklet()SharedWorker: ƒ SharedWorker()SourceBuffer: ƒ SourceBuffer()SourceBufferList: ƒ SourceBufferList()SpeechSynthesisErrorEvent: ƒ SpeechSynthesisErrorEvent()SpeechSynthesisEvent: ƒ SpeechSynthesisEvent()SpeechSynthesisUtterance: ƒ SpeechSynthesisUtterance()StaticRange: ƒ StaticRange()StereoPannerNode: ƒ StereoPannerNode()Storage: ƒ Storage()StorageEvent: ƒ StorageEvent()StorageManager: ƒ StorageManager()String: ƒ String()StylePropertyMap: ƒ StylePropertyMap()StylePropertyMapReadOnly: ƒ StylePropertyMapReadOnly()StyleSheet: ƒ StyleSheet()StyleSheetList: ƒ StyleSheetList()SubmitEvent: ƒ SubmitEvent()SubtleCrypto: ƒ SubtleCrypto()Symbol: ƒ Symbol()SyncManager: ƒ SyncManager()SyntaxError: ƒ SyntaxError()TaskAttributionTiming: ƒ TaskAttributionTiming()TaskController: ƒ TaskController()TaskPriorityChangeEvent: ƒ TaskPriorityChangeEvent()TaskSignal: ƒ TaskSignal()Text: ƒ Text()TextDecoder: ƒ TextDecoder()TextDecoderStream: ƒ TextDecoderStream()TextEncoder: ƒ TextEncoder()TextEncoderStream: ƒ TextEncoderStream()TextEvent: ƒ TextEvent()TextMetrics: ƒ TextMetrics()TextTrack: ƒ TextTrack()TextTrackCue: ƒ TextTrackCue()TextTrackCueList: ƒ TextTrackCueList()TextTrackList: ƒ TextTrackList()TimeRanges: ƒ TimeRanges()ToggleEvent: ƒ ToggleEvent()Touch: ƒ Touch()TouchEvent: ƒ TouchEvent()TouchList: ƒ TouchList()TrackEvent: ƒ TrackEvent()TransformStream: ƒ TransformStream()TransformStreamDefaultController: ƒ TransformStreamDefaultController()TransitionEvent: ƒ TransitionEvent()TreeWalker: ƒ TreeWalker()TrustedHTML: ƒ TrustedHTML()TrustedScript: ƒ TrustedScript()TrustedScriptURL: ƒ TrustedScriptURL()TrustedTypePolicy: ƒ TrustedTypePolicy()TrustedTypePolicyFactory: ƒ TrustedTypePolicyFactory()TypeError: ƒ TypeError()UIEvent: ƒ UIEvent()URIError: ƒ URIError()URL: ƒ URL()URLPattern: ƒ URLPattern()URLSearchParams: ƒ URLSearchParams()USB: ƒ USB()USBAlternateInterface: ƒ USBAlternateInterface()USBConfiguration: ƒ USBConfiguration()USBConnectionEvent: ƒ USBConnectionEvent()USBDevice: ƒ USBDevice()USBEndpoint: ƒ USBEndpoint()USBInTransferResult: ƒ USBInTransferResult()USBInterface: ƒ USBInterface()USBIsochronousInTransferPacket: ƒ USBIsochronousInTransferPacket()USBIsochronousInTransferResult: ƒ USBIsochronousInTransferResult()USBIsochronousOutTransferPacket: ƒ USBIsochronousOutTransferPacket()USBIsochronousOutTransferResult: ƒ USBIsochronousOutTransferResult()USBOutTransferResult: ƒ USBOutTransferResult()Uint8Array: ƒ Uint8Array()Uint8ClampedArray: ƒ Uint8ClampedArray()Uint16Array: ƒ Uint16Array()Uint32Array: ƒ Uint32Array()UserActivation: ƒ UserActivation()VTTCue: ƒ VTTCue()ValidityState: ƒ ValidityState()VideoColorSpace: ƒ VideoColorSpace()VideoDecoder: ƒ VideoDecoder()VideoEncoder: ƒ VideoEncoder()VideoFrame: ƒ VideoFrame()VideoPlaybackQuality: ƒ VideoPlaybackQuality()ViewTimeline: ƒ ViewTimeline()ViewTransition: ƒ ViewTransition()VirtualKeyboard: ƒ VirtualKeyboard()VirtualKeyboardGeometryChangeEvent: ƒ VirtualKeyboardGeometryChangeEvent()VisibilityStateEntry: ƒ VisibilityStateEntry()VisualViewport: ƒ VisualViewport()WGSLLanguageFeatures: ƒ WGSLLanguageFeatures()WakeLock: ƒ WakeLock()WakeLockSentinel: ƒ WakeLockSentinel()WaveShaperNode: ƒ WaveShaperNode()WeakMap: ƒ WeakMap()WeakRef: ƒ WeakRef()WeakSet: ƒ WeakSet()WebAssembly: WebAssembly {compile: ƒ, validate: ƒ, instantiate: ƒ, compileStreaming: ƒ, instantiateStreaming: ƒ, …}WebGL2RenderingContext: ƒ WebGL2RenderingContext()WebGLActiveInfo: ƒ WebGLActiveInfo()WebGLBuffer: ƒ WebGLBuffer()WebGLContextEvent: ƒ WebGLContextEvent()WebGLFramebuffer: ƒ WebGLFramebuffer()WebGLProgram: ƒ WebGLProgram()WebGLQuery: ƒ WebGLQuery()WebGLRenderbuffer: ƒ WebGLRenderbuffer()WebGLRenderingContext: ƒ WebGLRenderingContext()WebGLSampler: ƒ WebGLSampler()WebGLShader: ƒ WebGLShader()WebGLShaderPrecisionFormat: ƒ WebGLShaderPrecisionFormat()WebGLSync: ƒ WebGLSync()WebGLTexture: ƒ WebGLTexture()WebGLTransformFeedback: ƒ WebGLTransformFeedback()WebGLUniformLocation: ƒ WebGLUniformLocation()WebGLVertexArrayObject: ƒ WebGLVertexArrayObject()WebKitCSSMatrix: ƒ DOMMatrix()WebKitMutationObserver: ƒ MutationObserver()WebSocket: ƒ WebSocket()WebTransport: ƒ WebTransport()WebTransportBidirectionalStream: ƒ WebTransportBidirectionalStream()WebTransportDatagramDuplexStream: ƒ WebTransportDatagramDuplexStream()WebTransportError: ƒ WebTransportError()WheelEvent: ƒ WheelEvent()Window: ƒ Window()WindowControlsOverlay: ƒ WindowControlsOverlay()WindowControlsOverlayGeometryChangeEvent: ƒ WindowControlsOverlayGeometryChangeEvent()Worker: ƒ Worker()Worklet: ƒ Worklet()WritableStream: ƒ WritableStream()WritableStreamDefaultController: ƒ WritableStreamDefaultController()WritableStreamDefaultWriter: ƒ WritableStreamDefaultWriter()XMLDocument: ƒ XMLDocument()XMLHttpRequest: ƒ XMLHttpRequest()XMLHttpRequestEventTarget: ƒ XMLHttpRequestEventTarget()XMLHttpRequestUpload: ƒ XMLHttpRequestUpload()XMLSerializer: ƒ XMLSerializer()XPathEvaluator: ƒ XPathEvaluator()XPathExpression: ƒ XPathExpression()XPathResult: ƒ XPathResult()XRAnchor: ƒ XRAnchor()XRAnchorSet: ƒ XRAnchorSet()XRBoundedReferenceSpace: ƒ XRBoundedReferenceSpace()XRCPUDepthInformation: ƒ XRCPUDepthInformation()XRCamera: ƒ XRCamera()XRDOMOverlayState: ƒ XRDOMOverlayState()XRDepthInformation: ƒ XRDepthInformation()XRFrame: ƒ XRFrame()XRHitTestResult: ƒ XRHitTestResult()XRHitTestSource: ƒ XRHitTestSource()XRInputSource: ƒ XRInputSource()XRInputSourceArray: ƒ XRInputSourceArray()XRInputSourceEvent: ƒ XRInputSourceEvent()XRInputSourcesChangeEvent: ƒ XRInputSourcesChangeEvent()XRLayer: ƒ XRLayer()XRLightEstimate: ƒ XRLightEstimate()XRLightProbe: ƒ XRLightProbe()XRPose: ƒ XRPose()XRRay: ƒ XRRay()XRReferenceSpace: ƒ XRReferenceSpace()XRReferenceSpaceEvent: ƒ XRReferenceSpaceEvent()XRRenderState: ƒ XRRenderState()XRRigidTransform: ƒ XRRigidTransform()XRSession: ƒ XRSession()XRSessionEvent: ƒ XRSessionEvent()XRSpace: ƒ XRSpace()XRSystem: ƒ XRSystem()XRTransientInputHitTestResult: ƒ XRTransientInputHitTestResult()XRTransientInputHitTestSource: ƒ XRTransientInputHitTestSource()XRView: ƒ XRView()XRViewerPose: ƒ XRViewerPose()XRViewport: ƒ XRViewport()XRWebGLBinding: ƒ XRWebGLBinding()XRWebGLDepthInformation: ƒ XRWebGLDepthInformation()XRWebGLLayer: ƒ XRWebGLLayer()XSLTProcessor: ƒ XSLTProcessor()console: console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …}decodeURI: ƒ decodeURI()decodeURIComponent: ƒ decodeURIComponent()encodeURI: ƒ encodeURI()encodeURIComponent: ƒ encodeURIComponent()escape: ƒ escape()eval: ƒ eval()event: undefinedglobalThis: Window {window: Window, self: Window, document: document, name: '', location: Location, …}isFinite: ƒ isFinite()isNaN: ƒ isNaN()offscreenBuffering: trueparseFloat: ƒ parseFloat()parseInt: ƒ parseInt()undefined: undefinedunescape: ƒ unescape()webkitMediaStream: ƒ MediaStream()webkitRTCPeerConnection: ƒ RTCPeerConnection()webkitSpeechGrammar: ƒ SpeechGrammar()webkitSpeechGrammarList: ƒ SpeechGrammarList()webkitSpeechRecognition: ƒ SpeechRecognition()webkitSpeechRecognitionError: ƒ SpeechRecognitionErrorEvent()webkitSpeechRecognitionEvent: ƒ SpeechRecognitionEvent()webkitURL: ƒ URL()[[Prototype]]: Window
Uncaught TypeError: Cannot read properties of undefined (reading 'join')
    at 07-arrows-test1.html:25:32

(예시 2)

const gangwon = {
  resorts: ["용평","평창","강촌","강릉","홍천"],
  print: function(delay=1000) {
    console.log(this);       // gangwon
    setTimeout(function() {
      console.log(this);     // gangwon
      console.log(this.resorts.join(","))
    }.bind(this), delay)     // this를 gangwon에 바인딩
  }
}

gangwon.print()

gangwon 객체와 그 안의 print 메서드를 기준으로 this의 참조와 해당 바인딩

  1. console.log(this);
    • 이 코드는 여전히 print 함수 내부에서 실행되므로, thisgangwon 객체를 참조한다.
    • 바인딩 방식: 암시적 바인딩. 함수가 gangwon 객체의 메서드로 호출되었기 때문에, this는 해당 메서드를 포함하고 있는 객체인 gangwon 객체를 참조한다.
  2. setTimeout 내부의 console.log(this);
    • 여기서 this.bind(this) 메서드를 사용하여 명시적으로 gangwon 객체에 바인딩되었다. 따라서, 콜백 함수 내부에서의 this 참조는 gangwon 객체를 가리키게 된다.
    • 바인딩 방식: 명시적 바인딩. .bind() 메서드를 사용하여 this의 참조를 명시적으로 gangwon 객체에 설정하였다.
  3. console.log(this.resorts.join(","))
    • 이 코드도 setTimeout의 콜백 함수 내부에서 실행되지만, 이 함수의 this.bind(this)에 의해 gangwon 객체에 바인딩되었기 때문에. 그러므로, this.resortsgangwon 객체의 resorts 프로퍼티를 참조하게 되어 에러 없이 리조트 이름들을 출력하게 된다.
    • 바인딩 방식: 명시적 바인딩. .bind()를 통해 명시적으로 바인딩된 this 참조를 사용한다.

<출력 결과>

Objectprint: ƒ print()resorts: (5) ['용평', '평창', '강촌', '강릉', '홍천'][[Prototype]]: Object
Objectprint: ƒ print()resorts: (5) ['용평', '평창', '강촌', '강릉', '홍천'][[Prototype]]: Object
용평,평창,강촌,강릉,홍천

문자열 연결과 템플릿 문자열

  • 문자열을 연결하기 위해 사용하는 + 연산자는 가독성이 떨어짐
  • ES2015부터 ` (백틱) 사용 가능 (맥북 기준: ₩+option)
  • `` 안에 문자열과 ${계산식}을 혼용

 

함수 선언과 호출, 함수 표현식, 호이스팅

  • 호이스팅: (함수/변수 선언을 유효 scope의 최상단으로 이동) 자바스크립트(Javascript)에서 변수와 함수 선언이 그들이 있는 코드에서 상위로 끌어올려진 것처럼 작동하는 특성을 나타내는 용어
    • 함수 표현식을 쓰면 해당 함수가 먼저 선언 되었는지 확인 할 수 있다 (권장)
    • 함수 선언문에서는 해당 특성이 유효하나 함수 표현식, 화살표 함수에서는 불가능하다.
    • let, const는 호이스팅을 허용하지 않는다.
  • 예외 케이스: <script type="text/babel">: var도 호이스팅을 허용하지 않는다.

 

Default parameters

function logActivity(name="임준식", acivity="테니스"){
    console.log(`${name}은 ${acivity}를 좋아합니다.`)
}

logActivity()

var defaultPerson = {
    name: {
      first: "성원",
      last: "오"
    },
    favActivity: "테니스"
}

function logActivity2(p=defaultPerson){
    console.log(`${p.name.first}은 ${p.favActivity}를 좋아합니다.`)
}

logActivity2()

<출력 결과>

"임준식은 테니스를 좋아합니다."
"성원은 테니스를 좋아합니다."
 

화살표 함수

ES6 (ES2015)에서 도입된 새로운 함수 문법으로 화살표 함수는 전통적인 함수 표현 방식에 비해 더 간결하며, 몇 가지 중요한 특성도 가지고 있다.

// 전통적인 함수 표현
const square = function(x) {
  return x * x;
};

// 화살표 함수 표현
const squareArrow = x => x * x;
var lordify = firstname => `캔터베리의 ${firstname}`

console.log(lordify("임수한"))

var sum = (op1,op2) => op1+op2

console.log(sum(3,5))

<출력 결과>

"캔터베리의 임수한"

8

싱글턴 패턴

정의

하나의 인스턴스만을 가지는 class의 집합

static 키워드를 사용하여 구현 가능

메서드 실행 주체

클래스가 수행하는 메서드 → static

인스터스가 실행 → 일반

예제: 로그 출력기 만들기

의도: 모든 회원들의 입출금 내역을 파일에 저장

  • 계좌 클래스
public class Account {
    private int balance;
    private String owner;
    private Logger myLogger;
    public Account(String owner, int balance){
        this.balance = balance;
        this.owner = owner;
        this.myLogger = new Logger();
    }
    public String getOwner(){
        return owner;
    }
    public int getBalance(){
        return balance;
    }
    public void deposit(int money){
        myLogger.log("owner"+" : "+this.getOwner()+" deposit "+money);
        balance+=money;
    }
    public void withdraw(int money){
        if(balance >=money){
            myLogger.log("owner"+" : "+this.getOwner()+" withdraw "+money);
            balance-=money;
        }
    }
}
  • 로그 출력기 클래스
import java.util.Date;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

public class Logger{
    private final String LOGFILE = "log.txt";
    private PrintWriter writer;
    public Logger(){
        try{
            FileWriter fw = new FileWriter(LOGFILE);
            writer = new PrintWriter(fw, true);
        }catch (IOException e){}
    }
    public void log(String message){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date data = new Date(System.currentTimeMillis());
        writer.println(formatter.format(data)+ " : " + message);
    }
}

<문제점>

public class Main {
    public static void main(String[] args) {
        Account acct1 = new Account("Wuhan",1000000);
        acct1.deposit(20000);
        Account acct2 = new Account("YongGang",20000);
        acct2.withdraw(20000);
    }
}

해당 코드 실행시 뒤에 결과로인해 앞에 결과가 덮어 씌어짐으로 사용자의 모든 입출력이 찍히는 의도가 작동되지 않음 즉 본래의 의도와 벗어남

(해결책) 싱글톤 패턴으로 수정한 출력기 클래스들

Eager Initialization

이른 초기화: 인스턴스를 프로그램이 시작되자 마자 미리 생성

문제점: 클래스 로딩 시점에 초기화되어 인스턴스가 필요하지 않은 경우에도 생성

import java.util.Date;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

public class Logger{
    private static Logger instance = new Logger();
    private final String LOGFILE = "log.txt";
    private static PrintWriter writer;
    private Logger(){
        try{
            FileWriter fw = new FileWriter(LOGFILE);
            writer = new PrintWriter(fw, true);
        }catch (IOException e){}
    }
    public static Logger getInstance(){
        return instance;
    }
    public void log(String message){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date data = new Date(System.currentTimeMillis());
        writer.println(formatter.format(data)+ " : " + message);
    }
}

Lazy Initialization

늦은 초기화: Eager Initialization의 문제점을 해결하기 위해 인스턴스가 필요할 때 생성하는 방식

문제점: 다중 스레드 환경에서는 단일 인스턴스 생성이라는 싱글톤의 목적과는 다르게 여러 인스턴스가 생성될 위험이 있음

import java.util.Date;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

public class Logger{
    private static Logger logger;
    private final String LOGFILE = "log.txt";
    private static PrintWriter writer;
    private Logger(){
        try{
            FileWriter fw = new FileWriter(LOGFILE);
            writer = new PrintWriter(fw, true);
        }catch (IOException e){}
    }
    public static Logger getInstance(){
        if(logger==null)
            logger = new Logger();
        return logger;
    }
    public void log(String message){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date data = new Date(System.currentTimeMillis());
        writer.println(formatter.format(data)+ " : " + message);
    }
}

<문제점 예시>

import java.util.Random;

class User extends Thread{
    public User(String name){super(name);}
    public void run(){
        Random r = new Random();
        Account acct = new Account(Thread.currentThread().getName(), r.nextInt(1000000));
        if(r.nextBoolean()) acct.withdraw(r.nextInt(acct.getBalance()));
        else acct.deposit(r.nextInt(acct.getBalance()));
    }
}

public class Main {
    public static void main(String[] args) {
        User[] users = new User[10];
        for (int i = 0; i < 10; i++) {
            users[i] = new User("suhan"+i);
            users[i].start();
        }
    }
}

코드 실행 결과

Logger@6ba60d46
Logger@3b1b95ed
Logger@1e628db7
Logger@70282c99
Logger@6a07b062
Logger@148cd591
Logger@7f20d3a2
Logger@71eac517
Logger@f37a491
Logger@33306c50

 

해결책: synchronized 키워드

synchronized 키워드 사용: instance를 임계구역으로 설정 한다면 다중 스레드 환경에서의 문제점을 해결 할 수 있다.

문제점: 비용이 비싸다 제일 처음에만 synchronized로 임계구역으로 설정한게 필요하지 그 이후 부터는 공유자원으로 보호 하지 않아도 되기 때문에 비효율적인 방식이 되어 버린다.

public class Logger{
    private static Logger instance;
    private final String LOGFILE = "log.txt";
    private static PrintWriter writer;
    private Logger(){
        try{
            FileWriter fw = new FileWriter(LOGFILE);
            writer = new PrintWriter(fw, true);
        }catch (IOException e){}
    }
    synchronized public static Logger getInstance(){
        if(instance==null) instance = new Logger();
        return instance;
    }
    public void log(String message){
        System.out.println(this.toString());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date data = new Date(System.currentTimeMillis());
        writer.println(formatter.format(data)+ " : " + message);
    }
}

 

해결책: DCL(Double Check Locking)

임계구역(Critical Section)에 진입하기 전에 두 번의 검사를 수행하여 해당 객체가 이미 생성되었는지 확인하는 방법 synchronized 키워드 문장을 실행사기 전에 조건문을 사용하여 특정 조건이 수행되지 않았는지 체크하고 임계구역으로 설정한다.

문제점: DCL 방식을 사용하더라도 생성자를 통한 초기화를 하기 전 인스턴스에 접근 하는 문제가 발생 할 수 있다

+ 단 Logger instance 를 volatile 키워드를 사용하여 순서 변경을 막는다면 문제점이 없다.

 

해결책: Initialization on demand holder idiom

내부 클래스로 만들어 해당 클래스를 통해 인스턴스를 반환함으로서 위에서 발생 할 수 있는 생성자를 통한 초기화를 하기 전 인스턴스에 접근 하는 문제 해결

참조 하기 전 (메모리 적재 x) -> 참조 후 (메모리 적재) 내부 클래스임으로 바로 생성 (원자적 행위)임으로 끼어들기 불가능

import java.util.Date;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

public class Logger{
    private final String LOGFILE = "log.txt";
    private static PrintWriter writer;
    private Logger(){
        try{
            FileWriter fw = new FileWriter(LOGFILE);
            writer = new PrintWriter(fw, true);
        }catch (IOException e){}
    }

    private static final class LoggerHolder {
        private static final Logger instance = new Logger();
    }

    public static Logger getInstance(){
        return LoggerHolder.instance;
    }
    public void log(String message){
        System.out.println(this.toString());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date data = new Date(System.currentTimeMillis());
        writer.println(formatter.format(data)+ " : " + message);
    }
}

 

내용 요약

  • when: 단일 인스턴스로만 특정 클래스가 필요한 상황
  • how: static 키워드를 통해 정적 요소 생성 반환, private 접근 지정자로 생성자 외부 호출로 부터 보호
  • solve: 늦은 초기화(lazy initialization)을 활용하여 정적으로 클래스 본인 자체를 내부에 생성하고 호출시 처음 딱 한번 생성시키고 반환, 내부 클래스를 통해 로딩시 바로 해당 인스턴스가 생성되도록 구현
class SingleThon {
	// 생성자 private 접근 지정자로 외부 호출 제어
    private SingleThon(){}
    /* 
    
    그 밖에 맴버 변수 함수들..
    
    */
    private static final class InstanceHolder{
    	private static final SingleThon instance = new SingleThon();
    }
    // 처음 호출 시 딱 한번만 생성되고 그 이후는 기존에 있던 인스턴스 반환
    public static SingleThon getInstance(){
        return InstanceHolder.instance;
    }
}

 

'Development > Design Pattern' 카테고리의 다른 글

[Design Pattern] strategy 패턴 (OCP)  (0) 2023.09.18

 

+Add item 을 통해 내용 추가 후 

제목 클릭 이후 커스터마이징 가능

 

스프린트 뷰 추가

+ Recent posts