Example 1 — Setter
Validate on write.
JavaScript
class T { set n(v){ if (v < 0) throw new Error("neg"); this._n = v; } get n(){ return this._n; } }
const t = new T(); t.n = 3; console.log(t.n); How It Works
- Setter stores _n.
Use get name() and set name(v) to run code when a property is read or written, while callers still use normal property syntax.
class Temp {
constructor(c) { this._c = c; }
get f() { return this._c * 1.8 + 32; }
}
console.log(new Temp(0).f); Validate on write.
class T { set n(v){ if (v < 0) throw new Error("neg"); this._n = v; } get n(){ return this._n; } }
const t = new T(); t.n = 3; console.log(t.n); Defined once for all instances.
class A { get ok(){ return true; } }
console.log(new A().ok); Same get/set keywords.
const o = { get x(){ return 1; } }; console.log(o.x); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful