আপডেট আমার নীচের উত্তরটি সময় এবং আমার বোঝার উপযোগী একটি স্টাইলে 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 ।
মূল উত্তরটি নীচে রাখা হয়েছে (পরিবর্তনের ইতিহাসের পরিবর্তে) কারণ আমি মনে করি তুলনাটি মূল্যবান।
আপনি নিম্নলিখিত একটি স্পিন দিতে পারেন। এটি আপনাকে তার নির্মাতা বা অন্য কোথাও স্পষ্টভাবে কোনও আইটের আইডি সেট করার বিকল্প দেয়।
(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());
আপনি অভ্যন্তরীণভাবে ইউনিক আইডি সংরক্ষণের জন্য যে কোনও সদস্য ব্যবহার করবেন না কেন এটি অন্য কোনও স্বয়ংক্রিয়ভাবে তৈরি সদস্যের নামের সাথে সংঘর্ষ না ঘটে তা নিশ্চিত হয়ে নিন।