given this javascript code:
this.underlyingReference = {name: 'joe'};
this.nullMe(this.underlyingReference);
alert(this.underlyingReference.name);
function nullMe(variable) {
variable = null;
}
Is there a way in Javascript for me to null this.underlyingReference using "variable"? I want to be able to null out variable and have the underlying reference be nulled and not simply null the reference to a reference.
I've read articles like this one http://snook.ca/archives/javascript/javascript_pass about Javascript's pass by reference functionality but it appears as though when you want to destroy the underlying reference the behavior is not what I have come to expect from references.
when execution passes the second line of code I want "this.underlyingReference" to be nulled out. However the alert line shows that the underlying reference is still alive and kicking.
why not just assign null to that property:
this.underlyingReference = null;
alert(this.underlyingReference);// null
or, if you want to destroy the property, you can use delete:
delete this.underlyingReference;
alert(this.underlyingReference);// undefined
if you still want to have a function call, you can use this setup:
var NullMe = function(obj, propName)
{
obj[propName] = null;
//OR, to destroy the prop:
delete obj[propName];
}
NullMe(this, 'underlyingReference');
You can try
function nullMe(obj, reference){
delete obj[reference];
}
nullMe(this, "underlyingReference");
Or
function nullMe(reference){
delete this[reference];
}
nullMe.call(this, "underlyingReference");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With