Javascript - 如何清空底层引用?
给定这个 javascript 代码:
this.underlyingReference = {name: 'joe'};
this.nullMe(this.underlyingReference);
alert(this.underlyingReference.name);
function nullMe(variable) {
variable = null;
}
Javascript 有没有办法让我使用“variable”来 null this.underlyingReference ?我希望能够清空变量并清空底层引用,而不是简单地清空对引用的引用。
我读过这样的文章 http://snook.ca/archives/javascript/javascript_pass关于 Javascript 的传递引用功能,但似乎当您想要销毁底层引用时,该行为并不是我对引用的期望。
当执行通过第二行代码时,我希望“this.underlyingReference”被清空。然而,警报线显示底层参考仍然存在并且正在运行。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接将 null 分配给该属性:
或者,如果您想销毁该属性,可以使用删除:
如果您仍然想要进行函数调用,可以使用以下设置:
why not just assign null to that property:
or, if you want to destroy the property, you can use delete:
if you still want to have a function call, you can use this setup:
你可以尝试
或者
You can try
Or
在某些情况下,Pascal 和 C 中使用的“旧引用”与 java、javascript 和最新编程语言中的“引用”之间存在混淆。
在 javascript 中,传递一个值,该值是对对象的引用。这意味着您可以更改该引用后面的对象,但不能更改引用本身。
如果您需要在方法中执行此操作,那么您需要“显式”执行此操作,例如:
但是有一个方法来设置 null 有点过度设计:)
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 :
But it's a bit, well, over-engineering to have a method to set null :)