开发者

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 does开发者_运维知识库n'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:

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜