为什么我删除的功能不是typeof“undefined”在Node.js? [英] Why is my deleted function not typeof "undefined" in Node.js?

查看:72
本文介绍了为什么我删除的功能不是typeof“undefined”在Node.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js。

I'm using Node.js.

我的sum函数被删除后,我希望typeof(sum)返回undefined,但是它没有。

After my "sum" function gets deleted, I would expect the typeof(sum) to return "undefined", but it doesn't.

// functions are data in Javascript

var sum = function ( a,b ) { return a + b; }
var add = sum;
delete sum;
console.log ( typeof sum ); // should return undefined
console.log ( typeof add ); // should return function
console.log ( add( 1,2 ) ); // should return 3

我认为它应该返回:

undefined
function
3

但它会返回:

function
function
3


推荐答案

你不应该使用 delete 运算符标识符(在范围变量中,函数 - 作为 sum - 或函数参数)。

You shouldn't use the delete operator on identifiers (in scope variables, functions - as sum - or function arguments).

delete 运算符的目的是删除对象属性

The purpose of the delete operator is to delete object properties.

当您声明时变量一个函数声明或函数参数,在幕后这些标识符实际上是属于环境的属性记录它们被声明的当前范围。

When you declare a variable a function declaration or function arguments, behind the scenes these identifiers are actually a properties that belongs to the environment record of the current scope where they were declared.

这些属性在内部明确定义为不可配置,它们可以' Ť被删除。此外, delete 运算符的使用已经被误解,在ES5 Strict Mode上,它在标识符上的使用已被完全禁止, delete sum; 应抛出 ReferenceError

Those properties are explicitly defined internally as non-configurable, they can't be deleted. Moreover, the usage of the delete operator has been so misunderstanded that on ES5 Strict Mode, its usage on identifiers has been completely disallowed, delete sum; should throw a ReferenceError.

编辑

正如@SLacks在问题评论中指出的那样, delete 运算符可以处理来自Firebug控制台的标识符,这是因为Firebug使用 eval 来执行您在控制台中输入的代码,以及在 eval ,是 mutable ,这意味着它们可以被删除,这可能是允许程序员在运行时删除动态声明的变量与eval,例如:

As @SLacks noted in the question comments, the delete operator does work with identifiers from the Firebug's console, that's because the Firebug uses eval to execute the code you input in the console, and the variable environment bindings of identifiers instantiated in code executed by eval, are mutable, which means that they can be deleted, this was probably to allow the programmer to delete at runtime dynamically declared variables with eval, for example:

eval('var sum = function () {}');
typeof sum; // "function"
delete sum; // true
typeof sum; // "undefined"

您可以在控制台上看到这种情况:

You can see how this happens also on the console:

这可能就是你正在阅读的书中发生的事情,作者在基于 eval 的控制台上进行了测试。

And that's probably what happened with the book you are reading, the author made his tests on a console based on eval.

这篇关于为什么我删除的功能不是typeof“undefined”在Node.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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