Alexis Nikichine <alexis.nikichine@somedomain.fr> writes:
[color=blue]
> Today, I have a function:
>
> function f()
> {
> }
>[/color]
[color=blue]
> and am looking for a way of distinguishing, from inside f, whether it
> has been called with new, or not.[/color]
Since the only difference visible inside f will be the value of the
"this" operator, this will have to be sufficient. It cannot be
completely safe, but unless someone is deliberatly trying to cheat, it
should be fairly safe. Javascript has no language based protection
against malicious code.
You could try checking whether the value of "this" could be a new
object created with "new f()". E.g., check
this.constructor == f
or
this instanceof f
I can't see any way of ensuring that f.prototype is the first object
in the prototype chain, so the above can be tricked using, e.g.,
var fake = new f();
// fiddle with fake
f.call(fake); // can't see that fake is not a new object
Indeed, there shouldn't be a way to see it. The "new" operator creates
the object, but the call to "f" to initialize it afterwards is just a
normal function call (calling the [[Call]] method of the function).
/L
--
Lasse Reichstein Nielsen -
lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'