let o1 = Object.create({ x: 1, y: 2 });
console.log(o1.x + o1.y); // 3
let o2 = Object.create(null) // 아무것도 상속 x
let o3 = Object.create(Object.prototype) // Object prototype 을 상속 === {} , new Object()
let unitcircle = { r: 1 };
let c = Object.create(unitcircle);
c.x = 1;
c.y = 1;
c.r = 2;
unitcircle.r; // 1 프로토타입은 영향 x
// 장황하지만 명시적인 방법
let surname = undefined;
if (book) {
if (book.author) {
surname = book.author.surname;
}
}
// surname, null, undefined 중 하나를 가져오는 간결하고 관용적인 방법
surname = book && book.author && book.author.surname;
// ?. 사용한 할당 표현식
let surname = book?.author?.surname;
delect 연산자는 객체에서 프로퍼티를 삭제. 피연산자는 프로퍼티 접근 표현식이어야 한다.
let o = { x: 1 };
"x" in o;
"y" in o;
"toString" in o; // true 상속된 프로퍼티지만 포함되어있으므로
o.hasOwnProperty("x");
o.hasOwnProperty("y");
o.hasOwnProperty("toString"); // false : toString은 상속된 프러파티
o.propertyIsEnumerable("x")
o.propertyIsEnumerable("toString") // 자체 프로퍼티 x
Object.prototype.propertyIsEnumerable("toString"); // flase 열거 불가
let o = { x: undefined };
o.x != undefined; // false 프로퍼티가 존재하지만 정의 x
o.y != undefined; // false 프로퍼티가 존재x
"x" in o; // true : 존재
"y" in o; // false 존재 x
delete o.x; // x 삭제
"x" in o; // false 이제 존재 x
let o = { x: 1, y: 2, z: 3 };
o.propertyIsEnumerable("toString"); // false 열거 불가능
for (let p in o) {
console.log(p); // x, y, z,는 순회 하지만 toString은 x
}
for in 보다 객체의 프로퍼티 이름을 배열에 저장해서 for/of 루프를 사용하는 것이 더 쉬울 때가 많다.
객체의 프로퍼티를 다른 객체에 복사하는 것은 흔한일
let target = { x: 1 },
source = { y: 2, z: 3 };
for (let key of Object.keys(source)) {
target[key] = source[key]
}
Object.assign()라는 유틸리티 함수 지원
o = Object.assign({}, defaults, o);
// 또는
o = { ...defaults, ...o };
let s = { x: 1, y: 1 }.toString() // s == '[obkect Object]'
let s = { x: 1, y: 1 }.toString(); // s == '[obkect Object]'
let point = {
x: 1,
y: 2,
toString: function () {
return `(${this.x}, ${this.y})`;
},
};
String(point); // "(1, 2)" : 문자열로 변환할 때 toString()을 호출
객체를 문자열이 아닌 다른 기본 타입, 보통은 숫자로 변환 하려할 때
Date 클래스의 valueOf()는 날짜를 숫자로 변환.
let point = {
x: 1,
y: 2,
valueOf: function () {
return Math.hypot(this.x, this.y);
},
};
Number(point);
let point = {
x: 1,
y: 2,
toJSON: function () {
return this.toString();
},
};
JSON.stringify([point]); // '["(1, 2)"]'
번수 x와 y에 값을 저장했고 객체와 x와 y프로퍼티에도 그 값을 할당하고 싶다고할때
let x = 1, y = 2;
let o = { x, y }
간결하게 작성 가능
const PROPERTY_NAME = "p1";
function computePropertyName() {
return "p" + 2;
}
let p = {
[PROPERTY_NAME]: 1,
[computePropertyName()]: 2,
};
const extension = Symbol("my extension symbol");
let o = {
[extension]: {
/* 이 객체에 확장 데이터를 저장 */
},
};
o[extension].x = 0;