LoginSignup
0
0

More than 5 years have passed since last update.

(メモ)ES6で遅延評価を書きたかった

Posted at

ふと遅延評価の使い道をjs内で思いついたものの、
遅延評価を関数を使っていちいち()を書きたくなかったので、どうにかならないか考えた。

理想としては

const hoge = new Lazy(document.getElementById('text').innerText)

みたいに書きたかったけど、思いついた限りだと

class Lazy {
    constructor (func) {
    this._innerFunc = func
    this._value = undefined
  }

  get value () {
    if (this._value === undefined) {
        this._value = this._innerFunc()
    }
    return this._value
  }
}

// 現実
const hoge = new Lazy(() => document.getElementById('text').innerText)

みたいになった。具体的な挙動は下記のjsfiddleに載せました。
定義通りvalueを参照すると遅延評価を実行します。

おまけ(宣伝)

qiitaだけでなくブログもやっています。
こっちはメモで、向こうはpythonを中心にがっつりと書くって使い方をしています。

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