简体   繁体   中英

Javascript references and differences in memory allocation

Does the amount of memory allocated to each Javascript reference depend on the object/function its referencing? In other words, if I create a reference to a small object and then create a reference to a large object, how much will the references differ in allocated memory?

For example:

obj1 = {foo: "bar"}
ref1 = obj1
ref2 = window

What is the difference in memory allocation between ref1 and ref2 ?

Why I ask

I'm storing references using jQuery.data() in scoped context elements (see below) and I just want to be more aware of what I'm storing and how much I'm storing. Does jQuery.data() store the reference or create a new object? - (Possibly a new SO question)

My Coffeescript class:

class Renderer
  constructor: ->
    jQuery("<div/>", {class: "myScope", data: @}).appendTo("body")

In Javascript:

var Renderer;
Renderer = (function() {
  function Renderer() {
    jQuery("<div/>", {
      "class": "myScope",
      data: this
    }).appendTo("body");
  }
  return Renderer;
})();

No, JavaScript assignments do not copy objects, they copy references. There should be no difference between the ref1 and ref2 variables except they're pointing to different objects.

Does jQuery.data() store the reference or create a new object?

They store the reference, that's the whole point. It won't put a copy or serialisation of the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM