javascript多个对象实例的时间戳相同

javascript multiple object instance same timestamp

本文关键字:时间戳 实例 对象 javascript      更新时间:2023-11-13

我很好奇为什么这会为每个返回相同的时间戳。我认为对象应该有不同的标识符。?

/js/helpers/v01.js

var Tester = (function () {
    var object_id = 'Tester';
    var object_id_unique = (new Date().getTime()) + '-' + (new Date().getMilliseconds());
    var _this;
    /**
     *
     * @constructor
     */
    function Tester(obj_name) {
        this.name = obj_name;
        this.run();
    }
    Tester.prototype = {
        run: function () {
            "use strict";
            var $body = document.getElementsByTagName('body')[0];
            var $node = document.createElement('div');
            $node.innerHTML = '<lable>' + this.name + ': </lable>' + ' ' + object_id + '-' + object_id_unique;
            $body.appendChild($node);
        }
    };
    return Tester;
})();

这是页面

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="/js/helpers/v01.js"></script>
</head>
<body>
<script type="text/javascript">
    new Tester('A');
    setTimeout(function () {
        new Tester('B');
    }, 500);
</script>
</body>
</html>

我的输出返回这个

A: Tester-1385613846838-838
B: Tester-1385613846838-838

在闭包中,您将永久设置object_id_unique的值(因为函数在定义时立即调用,而不是在调用返回的函数时)-将其移动到返回的函数中。这应该解决它:

var Tester = (function () {
    var object_id = 'Tester';
    var _this;
    /**
     *
     * @constructor
     */
    function Tester(obj_name) {
        this.name = obj_name;
        this.run();
    }
    Tester.prototype = {
        run: function () {
            "use strict";
            var object_id_unique = (new Date().getTime()) + '-' + (new Date().getMilliseconds());
            var $body = document.getElementsByTagName('body')[0];
            var $node = document.createElement('div');
            $node.innerHTML = '<lable>' + this.name + ': </lable>' + ' ' + object_id + '-' + object_id_unique;
            $body.appendChild($node);
        }
    };
    return Tester;
})();

定义类时,您只创建了一次object_id_unique。如果你希望它在每个实例中都不同,你需要在构造函数中分配它。