- Objects and the dot2020년 08월 25일 18시 43분 55초에 업로드 된 글입니다.작성자: sue24
다른 프로그래밍 언어에서는 오브젝트와 함수를 두 가지 다른 것이라고 말하지만
자바스크립트에서는 두 개가 굉장히 밀접한 관련이 있다.
오브젝트는 어떤 형태로 우리의 컴퓨터 메모리상에 존재하고 있을까?
오브젝트는 property와 method를 가질 수 있다.
오브젝트는 property들의 집합으로
property는 name-value 페어의 집합이다.
value에는 boolean, number 등 기본 타입이나
또 다른 name-value 페어의 집합이 올 수 있다.
오브젝트는 함수를 가질 수도 있는데
이 함수를 method라고 한다.
함수이지만 오브젝트와 연결되어 있는 것!
오브젝트뿐 아니라 오브젝트에 딸린(?) property와 method도 메모리 주소가 있다.

이렇게 다른 메모리에 저장되어 있는 property나 method에는 어떻게 접근할 수 있을까?
var person = new Object(); person["firstname"] = "Tony"; person["lastname"] = "Alicea"; var firstNameProperty = "firstname"; console.log(person); console.log(person[firstNameProperty]);new Object(); 는 새로운 오브젝트를 만드는 문법이다.
person["firstname"] = "Tony";는 person이라는 오브젝트에
firstname이라는 property를 만들고 Tony라는 스트링 값을 부여한 것이다.
새로운 메모리 주소가 할당된 것이다.
여기에서 []는 computed member access 연산자!(왼 - 오 결합 법칙)
[]를 이용해서 property를 만들고 접근할 수 있다.
person이라는 오브젝트에서 [] 내부의 property나 method 이름을 찾는 연산자로
오브젝트에서 해당 property나 method가 없다면 새로 만드는 역할을 한다.
새로운 변수를 만들어서 그 변수를 []에 넘겨줄 수도 있다.
person 오브젝트 자체를 출력하면
person의 property인 firstname과 lastname도 나오는 것을 볼 수 있다.
console.log(person.firstname); person.address = new Object(); person.address.street = "111 Main St."; person.address.city = "New York"; person.address.state = "NY"; console.log(person.address.street); console.log(person.address.city); console.log(person["address"]); console.log(person["address"]["state"]);object의 property와 mehod에 접근하는 방식에는 []과 .이 있다.
해당 name에 맞는 메모리 주소를 찾아가는 방식이다.
. 역시 연산자로 member access 연산자이다.(왼 - 오 결합 법칙)
property를 ''로 감싸지 않아도 접근할 수 있어서 편하다.(''로 감싸면 안 된다!)
. 앞에 쓰인 object와 연결된 name들 중에서 . 뒤에 있는 것과 일치하는 것을 찾는 작업이다.
object 안에 새로운 오브젝트를 만들 수도 있다.
object.property.property처럼 연속해서 들어가는 것 역시 가능하다.
(object[property][property]도 가능!)
computed member access 연산자인 []나
member access 연산자인 .
둘 모두 왼쪽에서 오른쪽으로 간다.
제일 왼쪽에 있는 [] / .이 먼저 실행되는 함수이기 때문에 연속해서 들어가는 것이 가능하다.
person.address.city라고 하면
person이라는 object 안에 address라는 property를 찾고
address라는 property 안에서 city라는 property를 찾는 것이다.
두 번뿐 아니라 더 많이 들어가는 것 역시 가능하다.
'JS' 카테고리의 다른 글
amCharts5 튜토리얼 (0) 2022.06.08 함수도 오브젝트! (0) 2020.11.03 연산자의 우선순위와 결합법칙 (0) 2020.08.21 연산자는 함수다 (0) 2020.08.20 Type (0) 2020.08.17 다음글이 없습니다.이전글이 없습니다.댓글