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.
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.
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 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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With