Why is “this” in an anonymous function undefined when using strict?

It’s because, until ECMAscript 262 edition 5, there was a big confusion if people who where using the constructor pattern, forgot to use the new keyword. If you forgot to use new when calling a constructor function in ES3, this referenced the global object (window in a browser) and you would clobber the global object … Read more

How to removeEventListener that is addEventListener with anonymous function?

You can’t. You have to use a named function or store the reference somehow. var handler; function doSomethingWith(param) { handler = function(){ document.write(param); }; document.body.addEventListener(‘scroll’, handler,false); } setTimeout(function() { document.body.removeEventListener(‘scroll’, handler ,false); }, 3000); The best would be to do this in a structured way, so that you can identify different handlers and remove them. … Read more

removeEventListener on anonymous functions in JavaScript

if you are inside the actual function, you can use arguments.callee as a reference to the function. as in: button.addEventListener(‘click’, function() { ///this will execute only once alert(‘only once!’); this.removeEventListener(‘click’, arguments.callee); }); EDIT: This will not work if you are working in strict mode (“use strict”;)

Is it valid to define functions in JSON results?

No. JSON is purely meant to be a data description language. As noted on http://www.json.org, it is a “lightweight data-interchange format.” – not a programming language. Per http://en.wikipedia.org/wiki/JSON, the “basic types” supported are: Number (integer, real, or floating point) String (double-quoted Unicode with backslash escaping) Boolean (true and false) Array (an ordered sequence of values, … Read more

Why use named function expressions?

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. The variable you’re assigning it to has a name, but the function does not. (Update: That was true through ES5. As of ES2015 [aka ES6], often a function created with an anonymous expression gets a true name [but … Read more

Explain the encapsulated anonymous function syntax

It doesn’t work because it is being parsed as a FunctionDeclaration, and the name identifier of function declarations is mandatory. When you surround it with parentheses it is evaluated as a FunctionExpression, and function expressions can be named or not. The grammar of a FunctionDeclaration looks like this: function Identifier ( FormalParameterListopt ) { FunctionBody … Read more

Location of parenthesis for auto-executing anonymous JavaScript functions?

There isn’t any difference beyond the syntax. Regarding your concerns about the second method of doing it: Consider: (function namedfunc () { … }()) namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would … Read more