Reputation: 103
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.
Upvotes: 5
Views: 2307
Reputation: 236102
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 :)
Upvotes: 11
Reputation: 700622
Unless the constructor itself saves a reference to the object somewhere outside the object, there is no reference to the object longer, and the garbage collector will remove it.
The code isn't dangerous, it won't add anything to the global namespace, and it's not possible to reach the object unless the constructor makes it possible.
An example of where it could be used would be if the constructor registers the object itself:
var myHandlers = {};
function Handler(name) {
myHandlers[name] = this;
}
new Handler("test");
The drawback of using something like that is of course that it's harder to follow what's happening.
Upvotes: 5
Reputation: 3084
because there's no reference to it after its creation it is soon garbage collected.
just FYI: the reason for creating objects 80 to 90% of the time is so they can be referenced and utilized later.
Upvotes: 1