can-define-lazy-value
defineLazyValue(obj, prop, fn, writable)
Use Object.defineProperty to define properties whose values will be created lazily when they are first read.
var _id = 1;
function getId() {
return _id++;
}
function MyObj(name) {
this.name = name;
}
defineLazyValue(MyObj.prototype, 'id', getId);
var obj1 = new MyObj('obj1');
var obj2 = new MyObj('obj2');
console.log( obj2 ); // -> { name: "obj2" }
console.log( obj1 ); // -> { name: "obj1" }
// the first `id` read will get id `1`
console( obj2.id ); // -> 1
console( obj1.id ); // -> 2
console.log( obj2 ); // -> { name: "obj2", id: 1 }
console.log( obj1 ); // -> { name: "obj1", id: 2 }
Parameters
- object
{Object}
:The object to add the property to.
- prop
{String}
:The name of the property.
- fn
{function}
:A function to get the value the property should be set to.
- writable
{boolean}
:Whether the field should be writable (false by default).