LoginSignup
38
19

More than 5 years have passed since last update.

【JavaScript】オブジェクトリテラルの省略記法

Posted at

はじめに

ES2015を使用したオブジェクトリテラルの省略記法について説明します。
少しコードをスッキリ書く事ができます。

対象読者

・ES2015をこれから使っていきたい人

注意点

レガシーブラウザに対応させる場合は、トランスパイラ(Babel等)を使用し、ES5記法にトランスパイルをおこなってください。
(参考記事)
https://qiita.com/mizchi/items/3bbb3f466a3b5011b509#%E3%81%84%E3%81%BE%E3%81%99%E3%81%90es2015%E3%82%92%E4%BD%BF%E3%81%86
https://qiita.com/hietahappousai/items/9570da4b9275425489b2

省略記法

valueを省略できる(keyとvalueの変数名が同じ時)

【例】 ES5の書き方


const location = 'カリフォルニア';

const company = {
    name: 'google',
    location: location,
    getLocation: function() {
        return this.location;
    }
}
console.log(company.getLocation()); //カリフォルニア

【例】 ES2015での書き方


const location = 'カリフォルニア';

const company = {
    name: 'google',
    location,
    getLocation: function() {
        return this.location;
    }
}

console.log(company.getLocation()); //カリフォルニア

functionを省略できる

【例】 ES5の書き方

const location = 'カリフォルニア';

const company = {
    name: 'google',
    location,
    getLocation: function() {
        return this.location;
    }
}

console.log(company.getLocation()); //カリフォルニア

【例】 ES2015での書き方

//ES2015
const location = 'カリフォルニア';

const company = {
    name: 'google',
    location,
    getLocation() {
        return this.location;
    }
}

console.log(company.getLocation()); //カリフォルニア

使用例

なにかをPOSTする時

function postMessage(url, data) {
    $.ajax(
        {
         url,
         data,
         method: 'POST'
        }
    );
}

const url = 'https://xxxxxx';
const data = { text: 'xxxxxxxx' };

postMessage(url, data);
38
19
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
38
19