繁体   English   中英

如何在 javascript 中创建 object 的唯一实例?

[英]How do I create a unique instance of an object in javascript?

我一直在研究我自己的 javascript 库 kis-js。 我最近将它转换为与 jQuery 之类的 dom 选择器一起使用,但由于 javascript 仅复制引用我有这个问题:

如果您调用$_两次,则第二次调用它会更改第一次调用的结果。

测试代码:

<h1>Heading</h1>
<a>Anchor</a>
<script>
  var anchor = $_("a");
  var heading = $_("h1");
  console.log(anchor.el); // should be <a>, but it's <h1>
</script>

这是库的来源: https://github.com/timw4mail/kis-js/blob/master/kis.js

我在想我需要创建构造函数 object 的深层副本,但我不太确定如何 go 来解决这个问题。

编辑:

我创建了一个深拷贝 function:

dcopy = function(obj)
{
    var type, f;

    if(obj == null)
    {
        return;
    }

    if(typeof Object.create !== "undefined")
    {
        return Object.create(obj);
    }

    var type = typeof obj;

    if(type !== "object" && type !== "function")
    {
        return;
    }

    var f = function(){};

    f.prototype = obj;

    return new f();

};

如何使用它来扩展我构建的 object?

你应该返回一些new东西......另外,避免分配和返回全局变量。

所以,我只用了这个 function。

dcopy = function(obj) {
var type, f;

if(obj == null)
{
    return;
}

if(typeof Object.create !== "undefined")
{
    return Object.create(obj);
}

var type = typeof obj;

if(type !== "object" && type !== "function")
{
    return;
}

var f = function(){};

f.prototype = obj;

return new f();

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM