원문 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
자바스크립트는 간단한 객체 기반 패러다임을 기반으로 설계됐다. 객체는 속성들(properties)의 모음이며, 각 속성(property)은 이름(name)과 값(value)의 조합으로 구성된다. 프로퍼티의 값으로 함수를 사용 할 수 있는데, 이 프로퍼티를 메서드라고 한다. 이번 장에서 객체, 프로퍼티, 함수, 메서드를 살펴보고 직접 자신의 객체를 만들어 보도록 하겠다.
객체와 프로퍼티
자바스크립트의 객체는 자신의 프로퍼티를 가지고 있다. 객체의 프로퍼티는 객체에 첨부된(attached)된 일종의 변수로 설명할 수 있다. 실제 프로퍼티는 (그것이 객체에 첨부된다는 것을 제외하면) 일반적인 자바스크립트 변수와 동일하게 다룰 수 있다. 이 프로퍼티를 이용해서 객체의 특징을 정의 할 수 있다. 객체의 프로퍼티는 "."을 이용해서 접근 할 수 있다.
objectName.propertyName
자바스크립트 변수와 마찬가지로 객체이름과 프로퍼티이름은 대소문자를 구분한다. 프로퍼티를 정의하고 거기에 값을 할당 할 수 있다. myCar이라는 객체를 만들고 make, model, year이라는 프로퍼티를 정의하고 값을 할당한 예다.
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969
.....
function showProps(obj, objName) {
var result = "";
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
result += objName + "." + i + " = " + obj[i] + "\n"
}
}
return result;
}
console.log(showProps(myObj, "myObj"))
// 실행 결과
myObj.type = Dot syntax
myObj.date created = String with space
myObj.myString = String value
myObj.0.025307860923931003 = Random Number
myObj.[object Object] = Object
myObj. = Even an empty string
Enumerating all properties of an object
객체의 프로퍼티를 가져오기 위해서 3가지 방법을 사용 할 수 있다.
for...in loops
Object.keys(o) : 객체 o의 키를 가져온다.
Object.getOwnPropertyNames(o)
새 객체 만들기
자바스크립트에서 기본으로 제공하는 객체들외에 사용자가 직접 객체를 만들어서 사용할 수도 있다. 객체는 object initializer를 이용해서 만들 수 있다.
obj는 새로 만들 객체의 이름이다. property_i는 프로퍼티의 이름, value_i는 프로퍼티의 값이다. obj로 할당할지는 옵션이다. 만약 코드의 다른 곳에서 객체를 사용하지 않는다면, 할당 할 필요가 없다. 아래 예제는 3개의 프로퍼티를 만드는 myHonda 객체를 만들었다. 이중 engine 프로퍼티는 자신의 프로퍼티를 가지고 있다.
Contents
객체와 프로퍼티
..... function showProps(obj, objName) { var result = ""; for (var i in obj) { if (obj.hasOwnProperty(i)) { result += objName + "." + i + " = " + obj[i] + "\n" } } return result; } console.log(showProps(myObj, "myObj")) // 실행 결과 myObj.type = Dot syntax myObj.date created = String with space myObj.myString = String value myObj.0.025307860923931003 = Random Number myObj.[object Object] = Object myObj. = Even an empty stringEnumerating all properties of an object
새 객체 만들기
Object initializers 의 사용
var obj = { property_1: value_1, property_2: value_2, // ..., property_n: value_n, }var myHonda = { color:"red", wheels: 4, engine: { cylinders: 4, size: 2.2 } }; console.log(Object.keys(myHonda)) console.log(Object.keys(myHonda.engine))Constructor function의 사용
- 생성자 함수로 객체의 유형을 정의한다.
- new를 이용해서 객체로부터 새로운 인스턴스를 만든다.
객체의 타입을 정의하기 위해서는 이름과 프로퍼티, 메서드등을 정의해야 한다. 예를들어 car를 위한 객체 타입을 정의하려면, 호출하기 위한 함수와 make, model, year과 같은 프로퍼티가 필요하다.function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }var myCar = new Car("Eagle", "Talon TSi", 1993)var myCar = new Car("Eagle", "Talon TSi", 1993) var YourCar = new Car("Mazda", "Miata", 1990)function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } function Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; } var user_1 = new Person("yundream", "40", "male") var user_2 = new Person("joinc", "15", "male") var car_1 = new Car("Eagle", "Talon TSi", 1993, user_1) var car_2 = new Car("Nissan", "300ZX", 1992, user_2) consle.log(car_1.owner.name)Object.create 메서드 사용
var Animal = { type: "Invertebrates", displayType: function() { console.log(this.type) } } var animal_1 = Object.create(Animal); animal_1.displayType(); var fish = Object.create(Animal); fish.type = "Fishes"; fish.displayType();상속
Defining properties for an object type
Defining methods
Using this for object references
Defining getters and setters
Deleting properties
Comparing Objects
Recent Posts
Archive Posts
Tags