javascript中的唯一对象标识符 [英] unique object identifier in javascript

查看:132
本文介绍了javascript中的唯一对象标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做一些实验,我需要知道javascript中对象的某种唯一标识符,所以我可以看看它们是否相同。我不想使用相等运算符,我需要类似python中的id()函数。

I need to do some experiment and I need to know some kind of unique identifier for objects in javascript, so I can see if they are the same. I don't want to use equality operators, I need something like the id() function in python.

这样的事情是否存在?

推荐答案

更新我的原始答案是在6年前写成的,符合时代和我的理解。回应评论中的一些对话,更现代的方法如下:

Update My original answer below was written 6 years ago in a style befitting the times and my understanding. In response to some conversation in the comments, a more modern approach to this is as follows:

(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 的浏览器兼容性。

If you have archaic browser requirements, check here for browser compatibility for Object.defineProperty.

保留原始答案下面(而不仅仅是在变化历史中),因为我认为比较是有价值的。

The original answer is kept below (instead of just in the change history) because I think the comparison is valuable.

您可以进行以下操作。这也为您提供了在其构造函数或其他地方显式设置对象ID的选项。

You can give the following a spin. This also gives you the option to explicitly set an object's ID in its constructor or elsewhere.

(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的任何成员不会与之发生冲突另一个自动创建的成员名称。

Take care to make sure that whatever member you use to internally store the unique ID doesn't collide with another automatically created member name.

这篇关于javascript中的唯一对象标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆