如何在 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
我想我需要创建构造函数对象的深层副本,但我不太确定如何去做。
编辑:
我创建了一个深层复制函数:
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();
};
如何使用它来扩展我构造的对象?
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>
<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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该返回一些
new
...此外,避免分配和返回全局变量。You should return something
new
... Also, avoid assigning and returning global variables.所以,我就用了这个功能。
So, I just used this function.