When is an object in Javascript built?

Consider the following Javascript (1) function:

function setData(domElement) {
  domElement.myDataProperty = {
    'suppose': 'this',
    'object': 'is',
    'static': 'and',
    'pretty': 'big'
  };
};

Now, what I don't like about this function is that the same object is created every time the function is called. Since the object does not change, I would rather create it only once. Therefore, we could perform the following settings (2):

var dataObject = {
  'suppose': 'this',
  'object': 'is',
  'static': 'and',
  'pretty': 'big'
};

function setData(domElement) {
  domElement.myDataProperty = dataObject;
};

, script dataObject. , setData - , script, . , , , , , . , - , (3):

var dataObject;

function setData(domElement) {
  if (!dataObject) {
    dataObject = {
      'suppose': 'this',
      'object': 'is',
      'static': 'and',
      'pretty': 'big'
    };
  }
  domElement.myDataProperty = dataObject;
};

? , , . , !dataObject, , ? , Javascript ?

, , , . , , , , .. , , , : (1) (2) (2) (3)?

+3
5

: . , , . , - , - , . , , .

, ... . 1 000 000 , .

, . . . . , , , , .

, , ...

+2

- , , , , , :

function f() {
    return {a : "b", c: "d"};
}
o=f();
alert([o.c, o.e]); // Alerts "b,"
delete o.c;
o.e="f";
o=f();
alert([o.c, o.e]); // If the object was only created once this would produce ",f"

, , ? , .

:

var myFunction = (function(){
    var object = {a: "b", c: "d"};
    return function() { return object; }
})();

, , , , , .

+2

№2 .

, , .

( ), № 3.

"if", ... / - . - .

, ++ Java.

+1

-, .

-, , . , . -, , , , domElement.myDataProperty. , , ( ), , - .

+1

, .

+1

Source: https://habr.com/ru/post/1714936/


All Articles