开发者

javascript what happens on array push?

开发者 https://www.devze.com 2023-02-21 07:27 出处:网络
so I have: var something = function () { return 6} var foo = new something(); var arr = [] var arr2 = [] I do arr2.push(foo) and arr.push(foo)

so I have:

var something = function () { return 6}

var foo = new something();

var arr = []
var arr2 = []

I do arr2.push(foo) and arr.push(foo)

What happens in the background? Is foo dupl开发者_开发技巧icated and put in 2 places? Is foo just foo and what's inside the arrays a reference to foo?

Thanks.


EDIT: I misread. Because you are invoking the function with new you create a new object. Any object is passed by reference.

var something = function () { return 6}

var foo = new something();

typeof foo is an object so in this case it is passed by reference.

Pretty sure that foo is duplicated since it's a primitive and not an object.


What's inside the arrays are references to the same instance of something. This can be checked easily using for example chrome javascript console...

javascript what happens on array push?

As you can see adding a new member x to arr1[0] got it appearing on arr2[0].

0

精彩评论

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