user7739271
user7739271

Reputation:

Adding a property to an object by default

I want to add a Symbol property to an object for comparing.

Here is the way:

let _sym = Symbol('sym');

let a = {};
a[_sym] = Symbol('_');

let b = {};
b[_sym] = Symbol('_');

console.log(a[_sym] === b[_sym]); // false

Both a and b are objects. So, I can write:

let _sym = Symbol('sym');

Object.prototype[_sym] = Symbol('_');

Object.Equals = function (x, y) {
    return x[_sym] === y[_sym];
};

let a = {};
let b = {};

console.log(Object.Equals(a, b)); // true

But the result was changed.

What's wrong here?

Upvotes: 2

Views: 51

Answers (2)

webdeb
webdeb

Reputation: 13211

For example:

var a = {};
var b = {};

Different objects

a === b // false

The same underlying prototype

a.toString === b.toString // true

Upvotes: 0

pwolaq
pwolaq

Reputation: 6381

in the first case you assign to every object a new symbol instance

in the second, using prototype each object shares the same property, so they are equal

to compare, this code would be equal to the second case (but only for these 2 objects):

let _sym = Symbol('sym');
let val = Symbol('_');

let a = {};
a[_sym] = val;

let b = {};
b[_sym] = val;

console.log(a[_sym] === b[_sym]); // true

Upvotes: 4

Related Questions