I've been been learning Javascript over the past few months, and sometimes get the feeling that I'm writing code faster than I actually grasp the nuances of the language, so please bear with me here.
Anyway, my question pertains to the behavior of a certain methodology I've been using. The basic gist is to be able to design objects that can be constructed and used without using the "new" keyword.
Here's an example:
<!DOCTYPE html>
<html>
<head>
<script>
function example()
{
if(!(this instanceof example))
return new example();
}
example.prototype.test = function()
{
var
result = example();
if(result instanceof example)
{
console.log("Type: example");
if(result === this)
console.log("Unexpected: (result === this)");
else
console.log("Expected: (result !== this)");
}
else
console.log("Type: ?");
return result;
}
function run()
{
var
one = new example(),
two = example(),
three = one.test(),
four = two.test();
three.test();
four.test();
}
</script>
</head>
<body onload = "run()">
</body>
</html>
The output I get is:
Type: example
Expected: (result !== this)
Type: example
Expected: (result !== this)
Type: example
Expected: (result !== this)
Type: example
Expected: (result !== this)
...which is exactly what I want to see. My question, specifically, is whether or not it's:
(1) standard behavior
(2) supported by all browsers
(3) prone to any undesirable side-effects