Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  55] [ 3]  / answers: 1 / hits: 31901  / 13 Years ago, thu, february 9, 2012, 12:00:00

I'm wondering if this is even possible. Basically I have a couple objects that I pass to a function, and under certain conditions I want that function to set the object to null.



Ex.



var o = {'val' : 0};

f = function(v)
{
v = null;
};

f(o); // Would like this to set 'o' to null


Unfortunately it seems I can only set the function's argument to null. After calling the function 'o' will still refer to an object.



So, is it even possible to do this? And if so, how?


More From » function

 Answers
6

If you want to change the value of o when f(o) is called, you have two options:



1) You can have f(o) return a new value for o and assign that to o like this:



var o = {'val' : 0};
o = f(o);
// o == null


Inside of f(), you return a new value for o.



function f(v) {
if (whatever) {
return(null);
}
}


2) You put o into another object and pass a reference to that container object into f().



function f(v) {
if (whatever) {
v.o = null;
}
}

var c = {};
c.o = {'val' : 0};

f(c);
// c.o == null;


The javascript language does not have true pointers like in C/C++ that let you pass a pointer to a variable and then reach back through that pointer to change the value of that variable from within the function. Instead, you have to do it one of these other two ways. Objects and arrays are passed by reference so you can reach back into the original object from the function.


[#87577] Tuesday, February 7, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaleelh

Total Points: 661
Total Questions: 125
Total Answers: 103

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
;