Last active
November 8, 2016 17:28
-
-
Save LiuuY/cc798d0dd34df26beb3bd8ea6405fd33 to your computer and use it in GitHub Desktop.
JavaScript debugging tip: use a WeakMap to put a magic __id__ property on every object, use it in logs to uniquely identify objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://twitter.com/dan_abramov/status/794655915769266178 | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap | |
let ids = new weakMap() | |
let nextId = 1 | |
Object.defineProperty(Object.prototype, '__id__', { | |
get() { | |
if (!ids.has(this)) { | |
ids.set(this, nextId++) | |
} | |
return ids.get(this) | |
} | |
}) | |
var obj1 = {} | |
var obj2 = {} | |
console.log(obj1.__id__) // output: 1 | |
console.log(obj2.__id__) // output: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment