Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However the alert line shows that the underlying reference is still alive and kicking.

like image 457
omatase Avatar asked Dec 27 '22 15:12

omatase


2 Answers

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');
like image 95
Alex Pacurar Avatar answered Jan 09 '23 21:01

Alex Pacurar


You can try

function nullMe(obj, reference){
    delete obj[reference];
}

nullMe(this, "underlyingReference");

Or

function nullMe(reference){
    delete this[reference];
}
nullMe.call(this, "underlyingReference");
like image 37
Arun P Johny Avatar answered Jan 09 '23 19:01

Arun P Johny