LoginSignup
3
1

More than 5 years have passed since last update.

Proxyに触れる

Posted at

基本的な認識としましては、オブジェクトの動作を邪悪にするやつです。

const handler = {
  get(obj, prop) {
    return prop in obj ? obj[prop] : 100
  },
  set(obj, prop, value) {
    obj[prop] = value * 2
  }
}

const p = new Proxy({}, handler)

p.a = 1
p.b = 200

console.log(p.a) // => 2
console.log(p.b) // => 400
console.log(p.x) // => 100

new Proxy(ターゲット, ハンドラー)という感じで定義します。

上記の例では、代入時に数値を2倍、存在しないプロパティにアクセスすると100が返ります。

気持ち

基本的にショートハンドを提供する装置としての役割が大きいように見えます。
immerなどはこのProxyを使い、ミュータブルな操作でイミュータブルな処理が書けるようになっています。

何か面白い使い方ができそうですね。

3
1
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
3
1