追記: 2023-03-26
該当の記法は、分割代入 (Destructuring)
と呼ばれ、ES2015 に追加された言語仕様ということを教えてもらいました。
わからないので調べようにも、"javascript {} 代入" では満足な検索結果は得られなかったので、JavaScript を独習している人にとって優しくないよね。
何がわからないかというと
例えば、このページ Basic Features: Pages | Next.js に記載されているサンプルコードで、
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
export async function getStaticProps() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
の
export default function Blog({ posts }) {
に記述されている ({ posts })
がどういう挙動なのかわからなかった。
ということで、挙動を確認してみた
次のコードを JSFiddle で動作させてみた。
var test = 1;
var hoge = 'fuga';
var example = {
name: {
test,
test1: test,
hoge,
fiz: 'buzz',
},
};
console.log(example);
console.log('example.name.test has ' + example.name.test);
console.log('example.name.fiz has ' + example.name.fiz);
var {test1} = example.name
console.log('test1 has ' + test1);
func1 = function(obj) {
console.log('func1 prints out ' + obj.hoge);
}
func2 = function({ hoge, test }) {
console.log('func2 prints out ' + hoge);
}
func1(example.name);
func2(example.name);
cosole.log()
の出力結果は下記の通り。
{
name: {
fiz: "buzz",
hoge: "fuga",
test: 1,
test1: 1
}
}
"example.name.test has 1"
"example.name.fiz has buzz"
"test1 has 1"
"func1 prints out fuga"
"func2 prints out fuga"
感想
export default function Blog({ posts }) {
の挙動はなんとはなく想像は出来た。
しかし、次のような記述をする場合、
var {test1} = example.name
他の言語だと、
test1 = {
fiz: "buzz",
hoge: "fuga",
test: 1,
test1: 1
}
というような挙動を想定してしまう。
スプレッド構文とはまた違うのだろうし、この記法の正式な名称は何だろうか?`