0

Is there a way in JS to prevent object comparision?

Lets say i have:

function Person(data) {
  var that = {};
  that.name = data.name;
  return that;
}

let p = new Person({'name':'John'})

Now i want this to throw an error:

p == 2

1 Answers1

2

The only way I can think of is by relying on the fact that the comparison operator (==) uses string conversion to compare operands of different types:

function Person(data) {
  var that = {};
  that.name = data.name;
  return that;
}

let p = new Person({'name':'John'});

p.toString = function() {
  throw 'Error!';
}

p == 2

Of course, that would cause errors for all other string conversion of said object too, and it wouldn't work for the strict comparison operator (===).

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156