2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ES2015初見殺し

Last updated at Posted at 2018-06-03

ES2015の文法で、ググれないものたちを解説します。
const, import等、あるいは新規APIはググればわかるます。また、アロー関数など明らかに見た目が異質なので、知らなければそこで気づいて調べることができます。

しかし、そうでないものは意味を取り違えたまま先に進んでしまう可能性があります。

特にcurly bracket {} は、意味が多岐に渡りどれもよく使われるので注意が必要です。
(ブロックなのかオブジェクトリテラルなのか分割代入なのかJSXなのか...)。

アロー関数式(Arrow function expression)

通称「アロー関数」だが、関数ではない。

const f = (arg) => { return "Hello " + arg }
f("World")   // 'Hello World'

この例の場合、以下のような省略が可能。

const f = arg => "Hello " + arg 

es5

var f = function(arg) { return "Hello " + arg }

分割代入 (Destructuring assignment)

オブジェクトからプロパティをばらして代入します。
オブジェクトが持つ多くのプロパティから、必要なものだけを変数に代入できます。

const props = {
  name: '山田',
  age: 30,
  address: '大阪府',
}
const { name, address } = props

関数の仮引数でよく使用されます。
引数のオブジェクトがたくさんのプロパティを持っていて、そこから必要なプロパティだけを選択的に取得したい場合によく使います。

// 分配代入を使った仮引数
const f = ({ name, address } = {
  return name + ',' + address
}

const props = {
  name: '山田',
  address: '大阪府',
  tel: '012-345-6789',
  // その他たくさんのプロパティ...
}
f(props) //=> 山田,大阪府

Reactでの使用例

import文で使用される。

import { Component } from 'react';

class MyComponent extends Component {

は、以下と等価である。

import React from 'react';

class MyComponent extends React.Component {

関数の仮引数でもよく使用されます。
(propsなどから、その関数で必要なものだけを選択的に引数に取りたい場合)

const render = ({ name }) => {
  return <h1>Hello {name}!</h1>
}

これは以下のコードと等価である。

const render = (props) => {
  return <h1>Hello {props.name}!</h1>
}

スプレッド構文 (Spread syntax)

Reduxではオブジェクトを直接書き換えず、オブジェクトのコピーを作ることが多いので、もとのオブジェクトから一部を変更した新しいオブジェクトを作る用途によく使います。

const person = { name: '田中', age: 25 }
const personWithAddr = {
  ...person,
  address: '東京'
}
console.log(personWithAddr) //=> {name: "田中", age: 25, address: "東京"}

オブジェクトのプロパティや配列の要素を展開する。

プロパティ省略記法(Shorthand property names)

プロパティ名に変数名をそのまま使うことができます。
複数の変数をまとめてひとつのオブジェクトを構築するときによく使います。

const name = '田中'
const age = 25

const person = {
  name,
  age
}

console.log(person)  //=> { name: '田中', age: 25 }

省略記法を使わずに書くと以下のようになる。

const person = {
  name: name,
  age: age
}

省略記法と省略しないプロパティは混在してもよい。

const person2 = {
  name,
  age,
  address: '京都'
}
console.log(person)  //=> { name: '田中', age: 25, address: '京都' }
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?