开发者

Which JavaScript objects don't Deep Clone by default?

There's a lot of hubub about "cloning" JavaScript objects. However, as I understand it, it's a simple matter:

function clone(obj) {
    return obj;
}

No开发者_如何转开发w I realize that DOM objects aren't cloned this way, but as I understand it the DOM is part of the browser, not part of JavaScript.

What objects require deep-cloning and why?


That just returns a reference to the exact same object. It doesn't clone anything.

x = {}, 
c=function(o){return o}, 
y = c(x), 
result = (x === y)

result is true


This is in some respects a pass/assign by reference vs by value debate. By reference tends to be the default in most languages for anything that isn't a primitive for a number of reasons, probably chief amongst which are:

1) You're likely to churn through a lot of memory if each assignment / pass to a function creates a deep copy.

2) Extra fun when you're trying change the state of things... no more this.x = 5 if this.x is already bound. Probably something like this = this.clone({x: 5}) instead, if we were semi-lucky.

For more background, take a look at these two links:

http://oranlooney.com/functional-javascript/

http://oranlooney.com/deep-copy-javascript/

I think the real question should probably be -- why isn't there a nice convenient method of Object provided for doing deep copies?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜