Javascript - How to null the Underlying Reference?
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. Howeve开发者_运维知识库r 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");
There is a confusion between the "old by reference", used in Pascal and in C in some cases, and the "by reference" in java, javascript and most recent programming languages.
In javascript, a value is passed, and that value is a reference to the object. That mean you can change the object following that reference, but not change the reference itself.
If you need to do that in a method, then you need to do it "explicitly", for example :
this.nullMe("underlyingReference");
this.nullMe = function(name) {
this[name] = null;
}
But it's a bit, well, over-engineering to have a method to set null :)
精彩评论