如果您不将新对象分配给变量会发生什么?例如:
function MyConstructor() {
// Codes here
};
new MyConstructor(); // new object instance is not assign to a variable
这段代码危险吗?它会破坏全局命名空间吗?是否可以访问使用此样式创建的对象?
谢谢。
如果您不将新对象分配给变量会发生什么?例如:
function MyConstructor() {
// Codes here
};
new MyConstructor(); // new object instance is not assign to a variable
这段代码危险吗?它会破坏全局命名空间吗?是否可以访问使用此样式创建的对象?
谢谢。
正如您正确指出的那样,调用new MyConstructor()
将返回一个新对象,对它的引用不会被存储,因此会很快被垃圾收集器删除。您对该新对象采取行动的唯一机会是直接
new MyConstructor().someMethod();
...之后,您就失去了机会,新的对象引用在外太空中丢失了:)
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.
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.