开发者

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

I've been working on my own javascript library, kis-js. I recently converted it to work with dom selectors like jQuery, but because of javascript copying only references I have this issue:

If you call $_ twice, the second time you call it changes the result of the first call.

Test Code:

<h1>Heading</h1&g开发者_高级运维t;
<a>Anchor</a>
<script>
  var anchor = $_("a");
  var heading = $_("h1");
  console.log(anchor.el); // should be <a>, but it's <h1>
</script>

Here's the source to the library: https://github.com/timw4mail/kis-js/blob/master/kis.js

I was thinking I needed to create a deep-copy of the constructor object, but I'm not quite sure how to go about that.

Edit:

I created a deep copy 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();

};

How can I use this so that I can extend my constructed object?


You should return something new... Also, avoid assigning and returning global variables.


So, I just used this 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();

};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜