change value of a Number object

S

Stephan Walter

Hi,

I'm hacking on a LISP interpreter in JS [1], and running into trouble
with numbers and Number objects.

This is what I have:

var a = new Number(1);
var b = a;
document.writeln(a == b); // true
b = 2;
document.writeln(a == b); // false
document.writeln(a); // 1

Instead of replacing the *Number object* b with the *number* 2, I'd like
to assign 2 to the value of the Number object, which should still be
referenced by b *and* a. In other words, the two last lines should
output "true" and "2".

Regards,
Stephan Walter


[1] http://www.parkscomputing.com/lisptest.html (not by me)
 
M

Michael Winter

On 26/08/2005 22:02, Stephan Walter wrote:

[a = new Number(1); b = a;]
Instead of replacing the *Number object* b with the *number* 2, I'd like
to assign 2 to the value of the Number object, which should still be
referenced by b *and* a.

You cannot. Number objects are immutable. You would have to create a new
Number object and reassign to both a and b (otherwise the other would
still reference the original).

[snip]

Mike
 
L

Lasse Reichstein Nielsen

Stephan Walter said:
var a = new Number(1);
var b = a; ....
b = 2;
Instead of replacing the *Number object* b with the *number* 2, I'd
like to assign 2 to the value of the Number object,

Sorry, can't be done. The [[Value]] property of a Number object cannot
be assigned to, but is fixed at the time the object is created.
(Maybe some browser out there has added a way to change the value, but
it's not in the ECMAScript standard).

If you want an object holding a value, you can make your own "number
box":

function Box(value) {
this.setValue(value);
}
Box.prototype.toString = function() { return String(this.value); };
Box.prototype.valueOf = function() { return this.value; };
Box.prototype.setValue = function(value) { this.value = Number(value); }


var a = new Box(42);
var b = a;
b.setValue(37);
alert(b==a);
alert(a)


/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top