Javascript delete语句 [英] Javascript delete statement

查看:150
本文介绍了Javascript delete语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:我想解决为什么在此代码中有删除语句?

Q: I am trying to work out why there is a delete statement in this code?

我的假设是<$ c $

My assumption is foo will be dereferenced once statement has finished executing therefore would be no need to explicitly do it.

(function () {
    var foo = globalObject;

    foo.bar = function () {
        //code here
    }
    delete foo;
}());

推荐答案



< >解决方案

解决方案

请参阅本文何时和不使用 delete 运算符。

See this article on when To and Not To use the delete operator.

这似乎不是一个正确的用法。

This does not appear to be a proper use.

无法删除局部变量,因为它们在内部使用 DontDelete 属性标记。有时候你可能想清除一个局部变量(如果你想释放它所使用的任何内存,范围可能会在闭包中无限期地存活),但是你不使用 delete $

Local variables cannot be deleted as they are marked internally with the DontDelete attribute. There are occasions when you might want to clear a local variable (if you want to release any memory used by it and the scope may survive indefinitely in a closure), but you don't use the delete operator for this purpose - you can just set it to null.

在正常的函数中,不要创建闭包,任何局部变量只是在函数完成时被垃圾收集,如果在其他代码中没有其他引用他们的数据,该数据将被垃圾回收器释放。

In normal functions that don't create closures, any local variables will simply be garbage collected when the function completes and if there are no other references to their data in other code, that data will be freed by the garbage collector.

你只需要担心清除对数据的引用,那就是当你有一个范围存在很长一段时间(闭包或全局),你不再需要该数据,它是有用的释放其内存使用。

The only time you need to worry about clearing references to data is when you have a scope that will exist for a long duration of time (closure or global) and you no longer need that data and it's useful to free up its memory usage.

FYI, delete 操作符最常用的是从一个对象如:

FYI, the most common use of the delete operator is to remove a property from an object as in:

var foo = {x: 1, y: 2};
delete foo.x;

这篇关于Javascript delete语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆