상세 컨텐츠

본문 제목

property accessors, dot notation, bracket notation, 점 표기법, 대괄호 표기법, 속성접근자

JavaScript

by 폴리프레임 2024. 9. 16. 12:01

본문

반응형

속성접근자 (property accessors)

점 또는 괄호 표기법으로 객체의 속성에 접근할 수 있도록 해줍니다. 속성의 이름을 키로 사용하는 연관 배열(a.k.a 맵, 딕셔너리, 해시, 룩업 테이블)로 생각할 수 있습니다

 

1. 점 표기법 (dot notation) - 정적(static)

document.createElement("pre");
// createElement()라는 메소드를 document 객체에서 찾아서 호출하는 명령어
cv.onRuntimeInitialized = function() {
  console.log("Runtime initialized");
};

2. 대괄호 표기법 (bracket notation) - 동적(dynamic)

document["createElement"]("pre");
cv["onRuntimeInitialized"] = function() {
  console.log("Runtime initialized");
};

 런타임 중에 속성 이름을 동적으로 접근하거나 정의할 가능성이 있는 경우는 대괄호 표기법을 사용해야 합니다. 다음의 3가지의 경우입니다.

1. 속성이름이 변수일때

let dynamicPropertyName = "onRuntimeInitialized";
cv[dynamicPropertyName] = function() {
    console.log("OpenCV.js is ready!");
};

2. 조건에 따라 다른 속성 설정

let isDebugMode = true;
let callbackName = isDebugMode ? "onPrint" : "onRuntimeInitialized";

cv[callbackName] = function() {
    if (isDebugMode) {
        console.log("Debugging messages will be printed.");
    } else {
        console.log("OpenCV.js is initialized.");
    }
};

3. 속성이름을 반복적으로 생성

let events = ["onStart", "onProcess", "onComplete"];

events.forEach(eventName => {
    cv[eventName] = function() {
        console.log(eventName + " event triggered.");
    };
});

'JavaScript' 카테고리의 다른 글

properties(속성), attributes(특성) 차이점  (0) 2024.09.17
canvas.toDataURL()  (3) 2024.09.16
OpenCV, openCV.js  (3) 2024.09.16
HSL 색상 - Three.js, canvas, css  (1) 2024.09.13
구면좌표계, spherical coordinate system  (1) 2024.09.12

관련글 더보기