Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if the new instance object is not assign to a variable?

Tags:

javascript

What happens if you not assign new object to a variable? For example:

function MyConstructor() {
   // Codes here
};

new MyConstructor(); // new object instance is not assign to a variable

Is this code is dangerous? Does it clobber the global namespace? Is it possible to access the object created with this style?

Thanks.

like image 342
japt Avatar asked Feb 03 '13 13:02

japt


People also ask

What happens when you assign a value to a variable that has not been declared?

If you assign a value to a variable that you have not declared with var , JavaScript implicitly declares that variable for you. Note, however, that implicitly declared variables are always created as global variables, even if they are used within the body of a function.

What happens when you assign a value to a variable that has not been declared it will automatically become a global variable?

Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName , even if the value is assigned inside a function.

What happens when you assign an object to another object?

what happens when you assign one object to another object ?? It assigns the reference of the Object. In other words, both variables 'point' to the same Object. For example/ int [] a = new int[5]; int [] b = a; b and a now 'point' to the same array.

How do I set an instance variable in Python?

We can access the instance variable using the object and dot ( . ) operator. In Python, to work with an instance variable and method, we use the self keyword. We use the self keyword as the first parameter to a method.


1 Answers

  • Is this code is dangerous? - No.
  • Does it clobber the global namespace? - No.
  • Is it possible to access the object created with this style? - No.

As you correctly stated, the call new MyConstructor() will return a new object, the reference to it will just not get stored and will therefore get deleted by the garbage collector very quickly. Your only chance to act on that new object is directly

new MyConstructor().someMethod();

...after that, you've lost your chance and the new object reference is lost in outer-space :)

like image 97
jAndy Avatar answered Oct 26 '22 23:10

jAndy