Ala Eddine JEBALI
Ala Eddine JEBALI

Reputation: 7891

Is that a closure?

Is the code below a closure? Why?

var getContact = (function(){
	var person = {name: "John Doe"};
	return {aFriend: person};
})();
console.log(getContact.aFriend.name);
//outputs: John Doe

Upvotes: 0

Views: 91

Answers (3)

Rafique Ahmed
Rafique Ahmed

Reputation: 117

getContact is a IIFE ( immediately-invoked function expression) which returns an object. Here no inner function is created which refers to the outer function's environment variable. It should not be considered closure in my opinion, still waiting for explanation which can justify this as a closure.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075925

All JavaScript functions are closures; they keep a reference to the lexical environment object that's active when they're created. So technically there is briefly a closure created there, but in that code no closure endures for any length of time. The function is created, called, and then released; nothing maintains a reference to it, so it doesn't live on, and the lexical environment object it referenced can be reclaimed. Creating an object in a function does not give the object a reference to the function (or the environment object), so the function isn't retained, and so it doesn't retain its enclosing environment in memory.

Contrast with:

(function outer(x) {
    setTimeout(function inner() {
        alert(x);
    }, 100);
})("foo");

There, we create two closures (outer and inner) but outer is released almost immediately (like your example); inner is released 100ms or so later after the timer fires and the timer subsystem releases its reference to it.

Upvotes: 2

Quentin
Quentin

Reputation: 944556

No.

There is no function declared inside another function that is accessible after the outer function has finished executing.

In this example:

function createClosure() {
    var foo = 0;
    function bar() {
        alert(foo);
    }
    return bar;
}

var myFunc = createClosure();

… the variable foo is closed over so there is a closure.

Upvotes: 5

Related Questions