【问题标题】:How do I create a unique instance of an object in javascript?如何在 javascript 中创建对象的唯一实例?
【发布时间】:2011-07-12 12:29:46
【问题描述】:

我一直在开发自己的 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

我在想我需要创建构造函数对象的深层副本,但我不太确定如何去做。

编辑:

我创建了一个深拷贝函数:

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();

};

如何使用它来扩展我构造的对象?

【问题讨论】:

  • jQuery.extend 可以浅/深复制 JavaScript 对象。
  • @Paolo Moretti 这个库的重点是不使用 jQuery。
  • @timw4mail 我知道,但是你可以看看源代码,看看它是如何实现的。 github.com/jquery/jquery/blob/master/src/core.js
  • @Paolo Moretti @Danial A. White 我更新了这个问题。我发现“Javascript:权威指南”是一个很好的资源。

标签: javascript deep-copy


【解决方案1】:

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

【讨论】:

  • 好的,但是在哪里?选择器功能?构造函数?两者都有?
  • 如果我不分配全局变量,我将无法使用库。这是唯一分配的全局变量。
【解决方案2】:

所以,我只是使用了这个功能。

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();

};

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2012-05-10
    • 2021-11-23
    相关资源
    最近更新 更多