0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript オブジェクトリテラル

0
Posted at

自分でメソッドチェーンを作りたいと考えたときに調べていたら発見。
JavaScriptには、クラス定義をすっ飛ばして、いきなりオブジェクトから書き始める記法があるようだ。

オブジェクトリテラル

const user = {
    name: "田中",
    age: 20,
    greet() {
        console.log("こんにちは");
    }
};

この時点で

  • オブジェクトが生成される
  • インスタンス化はしていない
  • クラスも存在しない
    という状態。

メソッドチェーン

シンプルな例 オブジェクトリテラル利用

function compare(a, b) {
    return {
        result: a > b,

        errorIfFalse(message) {
            if (!this.result) {
                console.error(message);
            }
        }
    };
}

compare(3, 5)
    .errorIfFalse("3は5より大きくありません");

シンプルな例2 クラス利用

class Validator {

    constructor(result) {
        this.result = result;
    }

    errorIfFalse(message) {
        if (!this.result) {
            console.error(message);
        }
        return this;
    }

    errorIfTrue(message) {
        if (this.result) {
            console.error(message);
        }
        return this;
    }
}

function compare(a, b) {
    return new Validator(a > b);
}

とすると

compare(3, 5)
    .errorIfFalse("NG")
    .errorIfTrue("OK");
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?