extend Object
- ECMAScript2015에서 프로퍼티 명과 변수명이 같을 경우 프로퍼티를 생략할 수 있도록 개선되었다.
=> 확장된 객체
function createPerson(name, age) {
return {
name,
age
};
}
const person = createPerson("James Dean", 30);
function createPerson(name, age) {
return {
name,
age,
sayName: function() {
console.log(this.name);
}
};
}
const person = createPerson("James Dean", 30);
person.sayName();
function createPerson(name, age) {
return {
... 생략 ...
sayName() {
console.log(this.name);
}
};
}
const person = createPerson("James Dean", 30);
person.sayName();
Object Destructuring (객체, 배열 분해 할당)
- 객체 리터럴이나 배열을 해체해 최소단위의 변수로 저장하는 방법
- 기존에 객체리터럴이나 배열에서 데이터를 가져오는 방법
let node = {
type: "Identifier",
name: "foo"
};
let {type: localType, name: localName} = node;
console.log(localType, localName);
let {프로퍼티 명: 변수명, ...} = 객체 리터럴;
let colors = ["red", "green", "blue"];
let firstColor = "black";
let secondColor = "purple";
console.log(firstColor, secondColor);
[firstColor, secondColor] = colors;
console.log(firstColor, secondColor);
배열의 구조 분해시 객체의 분해처럼 괄호를 필요로하지 않는다.
구조 분해시 모든 배열의 개수를 맞출 필요가 없다. (단, 순서는 맞추어야 한다.)
function setAttribute(name, {url, method}) {
console.log("name", name);
console.log("url", url);
console.log("method", method);
}
setAttribute("searchForm", {
url: "http://localhost",
method: "post"
});
function setAttribute(name, {
url = "http://localhost",
method = "post”
} = {}) {
console.log("name", name);
console.log("url", url);
console.log("method", method);
}
setAttribute("searchForm");