VK wrote:
Rufnex wrote: i will init the object
var o = obj();
and if the argument isn't exist, i will destroy the oject automaticly.
You don't need to be so rude with the caller :-)
myConctructor(requiredArg) {
if (typeof requiredArg == 'undefined') {
return null;
// or:
// throw new Error('Argument is not optional');
}
else {
// construct an instance
}
}
This will not work as assumed by you. Not considering that the `function'
keyword is missing, returning a value explicitly from or throwing an
exception (which would either break the code where not supported or require
an adequate fallback) in the constructor will _not_ prevent an object from
being created.
Simple test case:
function Foo(x)
{
return x; // if you `throw' an exception, the return value
// would be `undefined', as if it was not thrown;
// the `new' keyword makes the difference
this.foo = "bar";
}
var x = new Foo(null); // try with any value as argument
// in JavaScript 1.5:
//
// "[Object object]
// object
// $constructor_code
//
// undefined"
alert([x, typeof x, x.constructor, x.foo, typeof x.foo].join("\n"));
Of course you could throw the exception and handle it later:
try
{
var x = new Foo(...);
}
catch (e)
{
// handle exception
}
However, as I wrote above, that requires exception support (JavaScript 1.5,
JScript 5.0, ECMAScript 3). Especially, to identify the specific exception
thrown, it could be required that the syntax
try
{
var x = new Foo();
}
catch (e if instanceOf Error) // replace Error with any constructor
{
// handle exception
}
is supported, which it is only in JavaScript 1.5+.
Therefore, for a general solution, I recommend that the returned reference
is checked for distinct true-value properties that should have been created
by the constructor (after the last conditional `return' or `throw'). If
not present or a false-value, the creation can be considered "failed" and
the respective entity referencing the object should be subject to the
`delete' operation (has no effect on declared variables) or should be
assigned `null'. The rest has to be left to the Garbage Collector.
PointedEars