简体   繁体   中英

Why is my deleted function not typeof “undefined” in Node.js?

I'm using Node.js.

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

I would think it should return:

undefined
function
3

But instead it returns:

function
function
3

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

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.

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 .

Edit :

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 .

delete is only for deleting properties of object notations and not for deleting the declared variables as per this article .

The snippet you have posted is there almost exactly as you've it here.

EDIT: The same article referenced above clarifies the inconsistency that appears in Firebug as well in this section . Relevant excerpt:

All the text in console seems to be parsed and executed as Eval code, not as a Global or Function one. Obviously, any declared variables end up as properties without DontDelete, and so can be easily deleted. Be aware of these differences between regular Global code and Firebug console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM