using delete

A

Andrew Poulos

Why is it that if I do this:

Foo = function() {
this.prop = true;
};
Foo.prototype.hi = function() {
alert("hi");
};
bar = new Foo();
delete bar;
bar.hi();

nothing gets alerted. But if I change the call to the constructor to

var bar = new Foo();

then the alert gets fired. And if I do this:

Foo = function() {
this.prop = true;
};
Foo.prototype.hi = function() {
delete this;
};
bar = new Foo();
bar.hi();

the object 'bar' does not seem to have been deleted? I'm testing with FF 2.

Andrew Poulos
 
R

Richard Cornford

Why is it that if I do this:

Foo = function() {
this.prop = true;};

Foo.prototype.hi = function() {
alert("hi");};

bar = new Foo();
delete bar;
bar.hi();

nothing gets alerted.

But you do get an error report (you should look at/for error reports).
But if I change the call to the constructor to

var bar = new Foo();

then the alert gets fired. And if I do this:

Variables declared in function or global execution contexts are marked
with the - DontDelete - attribute and so cannot be deleted (the delete
operation evaluates as false instead of true to indicate its falure
(sort of)).
Foo = function() {
this.prop = true;};

Foo.prototype.hi = function() {
delete this;};

bar = new Foo();
bar.hi();
Why would it? You have attempted to delete - this -, which is not
possible as - this - does not evaluate as a Reference type (it is a
value that is a reference to an object), and so the delete operator
does not act at all (but the delete expression still evaluates as true
in this case).

In any event, the - delete - operator works only by removing
properties from objects (where they are not marked as - DontDelete -)
and whatever object is referred to by - this - does not know which
properties of other objects (including Variable objects) may refer to
it, if any).

Richard.
 
P

pcx99

Richard said:
Variables declared in function or global execution contexts are marked
with the - DontDelete - attribute and so cannot be deleted (the delete
operation evaluates as false instead of true to indicate its falure
(sort of)).

Interesting gotcha.
 
R

Richard Cornford

pcx99 said:
Interesting gotcha.

Why is that a "gotcha"? There is no particularly good reason for wanting
to delete declared variables so not being able to is is hardly an
inconvenience.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top