Javascript - How to remove a base link?

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 a "variable"? I want to be able to nullify a variable and have a base link, and not just reference the link.

I read articles like this http://snook.ca/archives/javascript/javascript_pass about skipping Javascript by reference, but it seems that if you want to destroy the underlying link, the behavior is not what I expected from the links.

when execution passes the second line of code, I want this.underlyingReference to be canceled. However, the warning line indicates that the base link is still alive and kicking.

+4
source share
3 answers

You can try

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

or

 function nullMe(reference){ delete this[reference]; } nullMe.call(this, "underlyingReference"); 
+3
source

why not just null this 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 setting:

 var NullMe = function(obj, propName) { obj[propName] = null; //OR, to destroy the prop: delete obj[propName]; } NullMe(this, 'underlyingReference'); 
+4
source

There is some confusion between the "old by reference" used in Pascal and C in some cases, and "by reference" in java, javascript and the latest programming languages.

A value is passed in javascript, and that value is a reference to an object. This means that you can change the object after this link, but not change the link itself.

If you need to do this in a method, 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 way to set null :)

+3
source

Source: https://habr.com/ru/post/1369484/


All Articles