j obe
j obe

Reputation: 2039

Is this a closure or something different?

I came across this function about module patterns while I was learning about closures earlier, from what I understand this feels like a closure as Salary is still in scope with the method thats returned with the object but are the other variables still in scope as a closure e.g. name and age or are they destroyed once the object is returned? I thought that because the object references those variables then maybe all the variables are kept alive as part of the closure but not sure.

function EmployeeDetails() {
  var name: "Mayank";
  var age = 30;
  var designation = "Developer",
  var salary = 10000;

  var calculateBonus = function(amount) {
    salary = salary + amount;
  }

  return {
    name: name,
    age: age,
    designation: designation,
    calculateBonus: calculateBonus
  }
}

var newEmployee = EmployeeDetails()

var userName = newEmployee.calculateBonus(1000);

Upvotes: 1

Views: 51

Answers (1)

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

In terms of where the closure is :-

Here calculateBonus is the function which ultimately closes over salary and that's it. Since neither of name,age and designation are being used inside calculateBonus, the JavaScript Engine will optimize them out of the closure.

The following bit has nothing to do with closure :-

They (name,age and designation) are copied as properties of a new object that you returned explicitly from the EmployeeDetails function. So even if you change, say, newEmployee.name = 'Frank', you're just changing the property name on that object and not the name that was declared inside the EmployeeDetails function. That inside name is lost once that object got returned because it was a variable that stayed local to this function and didn't get closed over (precisely, used inside) by any other function.

The interesting bit :-

As per the Spec on which JS is based, the internal function (calculateBonus) technically closes over all the variables of it's outer scope irrespective of whether they are used or not used inside that function but the JS engines are smart enough to detect that and optimize them out of the closure.

Upvotes: 1

Related Questions