I want create new number object with own properties from Number. But when assign a number value to my variable, my variable turn to Number(primitive wrapper object).and loss own properties.How can I prevent this? Example
class Fnumber extends Number {
value = 0;
[Symbol.toPrimitive](hint) {
if (hint === 'object') {
return this;
}
return this.value;
};
//I don't want use Number.prototype.add method because this effect all Number values.
add = function(...v) {
this.value = Array.prototype.slice.call(arguments).reduce((o, v) => o v)
}
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr); //return a Object
console.log(nmbr 4); //return 14 is number
nmbr = 14;
console.log(nmbr); //return not a Object its Primative number value
console.log(nmbr 4); //return 14 a number
nmbr.add(4, 2, 4); //raise error.
CodePudding user response:
When doing nmbr = 14
you assign 14
to nmbr
, you are not changing the nmbr.value
, you are overwriting the object. Instead call add
and use nmbr.value
when needed.
class Fnumber extends Number {
value = 0;
add(...v) {
this.value = Array.prototype.slice.call(arguments).reduce((o, v) => o v)
}
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr.value);
nmbr.add(5);
console.log(nmbr.value);
nmbr.value = 25; // assign a value to nmbr.value
console.log(nmbr.value);
If you are not planning on reassigning the object, a good practice is to use const
instead of var
, see the error below.
class Fnumber extends Number {};
const nmbr = new Fnumber();
nmbr = 14;
CodePudding user response:
I found the solution indirectly.
class Fnumber extends Number {
value = 0;
add(...v) {
this.value = Array.prototype.slice.call(arguments).reduce((o, v) => o v)
}
}
//temğrary variable description
var _nmbr=new Fnumber();
//Define nmbr variable in global scobe
Object.defineProperty(window,"nmbr",{
enumerable: true,
configurable: true,
get() { return _nmbr; },
set(val) { if (typeof val=="number")_nmbr.value=val; }
});
nmbr=4;
console.log(nmbr 2);//output 6
//still nmbr variable is object,because assigned value to _nmbr.value with above set method
nmbr.add(4, 2, 4);
console.log(nmbr 2);//output 16