You cannot do it in a portable way. However if you think about it, if the purpose of delete foo.x;
is to reset the value of x
, you could provide a reset()
method on foo
that will restore missing properties to their default values.
// Object creation and initialisation
(foo=function()
{
alert("called");
}).reset = function()
{
if(!("x"in this)) this.x=42;
};
foo.reset();
// Using our callable object
alert(foo.x); // 42
foo(); alert(foo.x); // called; 42
foo.x=3; foo.reset(); alert(foo.x); // 3 [*]
delete foo.x; foo.reset(); alert(foo.x); // 42
(Tested in Chromium and Internet Explorer, but this should work in all browsers.)
In the line marked with [*]
the call to reset
is really not necessary, but it's there to demonstrate that it doesn't matter if you call it accidentally, and that this generalises to more than one property easily.
Note that in the function body of our callable object this
will refer to the containing scope, which will probably not be that useful to us since we'll want the function body to access the object members. To mitigate this, wrap it in a closure like this:
foo = (function()
{
var self = function()
{
self.x = 42;
};
return self;
})();
foo(); alert(foo.x); // 42