ZomoXYZ
ZomoXYZ

Reputation: 1852

Prototype change original

I have a prototype function that changes Boolean true to false and visa versa.

Boolean.prototype.switch = function() {
    return this.toString() === 'false';
};

And currently I have to use the following to change the original value.

var a = true;
a = a.switch();

Is there a way I can change the original variable (a) without a =? Meaning the script below run the same as above?

var a = true;
a.switch();

I am creating a quick game, and in the game there are 25 blocks which can have a value of on or off, or as I made it, true or false. When you click the block it switches values. While I was making the code to switch the values, I became a bit curious to if there is a way to remove a = and still change the value.

Note I am not asking for help with how to make this prototype function, I am asking if there is a way to change the value without a left hand side in an assignment

Upvotes: 2

Views: 247

Answers (2)

RobG
RobG

Reputation: 147383

You could implement your own object with the desired behaviour, however be careful of strict equality:

// Constructor
function MyBool(trueOrFalse) {
  this.value = !!trueOrFalse;
}

// Switch method
MyBool.prototype.switch = function() {
  this.value = !this.value;
}

// Custom valueOf and toString methods to act like a primitive
MyBool.prototype.valueOf = function() {
  return this.value;
}

MyBool.prototype.toString = function() {
  return '' + this.value;
}

// Initialise as false
var a = new MyBool(false);
document.write('a is currently: ' + a);
 
// Switch to true
a.switch()
document.write('<br>a is now: ' + a);

// Use in expression
document.write('<br>a == true? : ' + (a == true)) 
document.write('<br>a === true? : ' + (a === true)) // Ooops!
document.write('<br>!!a === true? : ' + (!!a === true)) // Work around
document.write('<br>in contional : ' + (a? 'true'  : 'false')) 

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

No, that's not possible - Boolean objects are effectively immutable.

You cannot assign to this in a method, and nor does the Boolean object expose any method to change its own value that you might have called.

Upvotes: 1

Related Questions