What does "rework" actually mean in this piece of code?
On MDN, I found the following piece of code with a comment saying "reusing the same object":
// recycling same object
function withValue(value) {
var d = withValue.d || (
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: null
}
);
d.value = value;
return d;
}
Can anyone use simple language to explain a little what this piece of code does? This is not so obvious to a beginner. Thank.
And source url: enter link here
Also, instead of putting the d
on function withValue
, why not put it in the prototype withValue
like:
var d = withValue.prototype.d || ( ...
What are the main considerations here?
source to share
The first time the function is called, it will create a new variable 'd' and assign it to itself. In OOP, a function withValue
will be like a class, but d
will be like a static member.
console.log(withValue.d); //undefined
var x = withValue(5);
console.log(x.value); //5
console.log(withValue.d.value); //5
console.log(x === withValue.d); //true
Variable x
and variable withValue.d
are references to the same object:
withValue.d.value = 1;
console.log(x.value); //1
If I called again withValue
, it would recycle or reuse the existing static member (withValue.d) and update its value:
var y = withValue(8);
console.log(withValue.d.value, y.value, x.value); //8 8 8
console.log(x === y, x === withValue.d, y === withValue.d); //true true true
Update: if there withValue
were:
function withValue(value) {
var d = {
enumerable: false,
writable: false,
configurable: false,
value: null
};
withValue.d = d;
d.value = value;
return d;
};
Then each function call will create a new object:
var x = withValue(1);
var y = withValue(2);
console.log(withValue.d.value, y.value, x.value); //2 2 1
console.log(x === y, x === withValue.d, y === withValue.d); //false false true
y.value = 999;
console.log(withValue.d.value, y.value, x.value); //999 999 1
So now 2 objects are being created - one of them refers to y
and withValue.d
, and the other to x
. In the first case, these three variables referred to the same object.
source to share
It is specified as a helper function to define a property descriptor object to use as the third argument to the tool Object.defineProperty()
.
On this first run, it assigns a private default property to the function withValue
, which forces the Object.defineProperty()
addition of an immutable property that is not enumerable, not writable, and not configurable, and with a value passed to the function withValue
.
So the following code:
var obj = {};
Object.defineProperty(obj, "newProp", withValue(10));
console.log(obj); // <- Object {newProp: 10}
assigns a obj
property with a name newProp
that cannot be enumerable, not writable, and not with a value of 10.
source to share