อัปเดตคำตอบเดิมของฉันด้านล่างนี้เขียนขึ้นเมื่อ 6 ปีที่แล้วในรูปแบบที่เหมาะสมกับเวลาและความเข้าใจของฉัน เพื่อตอบสนองต่อการสนทนาในความคิดเห็นแนวทางที่ทันสมัยกว่านี้มีดังนี้:
(function() {
if ( typeof Object.id == "undefined" ) {
var id = 0;
Object.id = function(o) {
if ( typeof o.__uniqueid == "undefined" ) {
Object.defineProperty(o, "__uniqueid", {
value: ++id,
enumerable: false,
// This could go either way, depending on your
// interpretation of what an "id" is
writable: false
});
}
return o.__uniqueid;
};
}
})();
var obj = { a: 1, b: 1 };
console.log(Object.id(obj));
console.log(Object.id([]));
console.log(Object.id({}));
console.log(Object.id(/./));
console.log(Object.id(function() {}));
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
console.log(k);
}
}
// Logged keys are `a` and `b`
หากคุณมีความต้องการเบราว์เซอร์โบราณตรวจสอบที่นี่Object.definePropertyสำหรับความเข้ากันได้สำหรับเบราว์เซอร์
คำตอบเดิมถูกเก็บไว้ด้านล่าง (แทนที่จะอยู่ในประวัติการเปลี่ยนแปลง) เพราะฉันคิดว่าการเปรียบเทียบมีคุณค่า
คุณสามารถหมุนได้ดังต่อไปนี้ นอกจากนี้ยังช่วยให้คุณมีตัวเลือกในการตั้งค่า ID ของวัตถุอย่างชัดเจนในตัวสร้างหรือที่อื่น ๆ
(function() {
if ( typeof Object.prototype.uniqueId == "undefined" ) {
var id = 0;
Object.prototype.uniqueId = function() {
if ( typeof this.__uniqueid == "undefined" ) {
this.__uniqueid = ++id;
}
return this.__uniqueid;
};
}
})();
var obj1 = {};
var obj2 = new Object();
console.log(obj1.uniqueId());
console.log(obj2.uniqueId());
console.log([].uniqueId());
console.log({}.uniqueId());
console.log(/./.uniqueId());
console.log((function() {}).uniqueId());
ดูแลให้แน่ใจว่าสมาชิกที่คุณใช้เก็บ ID เฉพาะไว้ภายในจะไม่ชนกับชื่อสมาชิกอื่นที่สร้างขึ้นโดยอัตโนมัติ