CodeQL 文档

删除非属性

ID: js/deletion-of-non-property
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - reliability
   - maintainability
   - language-features
   - external/cwe/cwe-480
Query suites:
   - javascript-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

delete 运算符应该只用于从对象中删除属性。使用它来删除变量会使代码难以维护,并且会在严格模式下出现错误。

建议

如果您要删除的变量是全局变量,这表明您的代码过度依赖全局状态。尝试通过在“JavaScript: The Good Parts”中介绍的模块模式之一来封装此全局状态。

示例

在以下代码片段中,delete 用于清理函数 get 使用的全局 cache 变量。

var cache;

function init() {
	cache = {};
}

function done() {
	delete cache;
}

function get(k) {
	k = '$' + k;
	if (!cache.hasOwnProperty(k))
		cache[k] = compute(k);
	return cache[k];
}

function compute(k) {
	// compute value for k
	// ...
}

更清晰的做法是将整个模块包装到闭包中,如下所示(这也避免将函数 compute 暴露到外部世界)

(function(global) {
	var cache;

	global.init = function init() {
		cache = {};
	};

	global.done = function done() {
	};

	global.get = function get(k) {
		k = '$' + k;
		if (!cache.hasOwnProperty(k))
			cache[k] = compute(k);
		return cache[k];
	}

	function compute(k) {
		// compute value for k
		// ...
	}
}(this));

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私