JavaScript - 如何/我可以将函数中的对象引用设置为null? [英] JavaScript - How/Can I set an object reference to null from a function?
问题描述
例。
var o = {'val':0};
f =函数(v)
{
v = null;
};
f(o); //想这样设置'o'为空
不幸的是,我似乎只能设置函数的参数为null。在调用函数'o'后,仍然会引用一个对象。
那么,甚至有可能这样做?如果是这样,怎么做?
如果你想改变 o $ c的值$ c>当调用 f(o)
时,您有两个选择:
<1> code> f(o)
为o返回一个新值,并将其赋值给o: var o = {'val':0};
o = f(o);
// o == null
内部 f()
,您会为 o
返回新值。
if(whatever){
return(null);
$ b $ 2你把o放到另一个对象中,将该容器对象引用到f()
。function f v){
if(whatever){
vo = null;
}
}
var c = {};
c.o = {'val':0};
f(c);
// c.o == null;
JavaScript语言没有类似于C / C ++的真正指针,它可以让指针传递给变量,然后通过该指针返回以更改函数内该变量的值。相反,你必须通过其他两种方式之一来完成。对象和数组通过引用传递,因此您可以从函数返回原始对象。
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?
解决方案If you want to change the value of
o
whenf(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 foro
.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.
这篇关于JavaScript - 如何/我可以将函数中的对象引用设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!