Search code examples
javascriptencapsulation

Javascript Is it possible to declare functions in a return?


According to this article (https://www.intertech.com/Blog/encapsulation-in-javascript/) the following code is an example of encapsulation in JS. What it does is basically restrict the possibility of modifying the variable fullName, so only if the new fullName does not have numbers it can be changed.

  var person = (function () {

  var fullName = "Jason Shapiro";
  var reg = new RegExp(/\d+/);

  return {
    setFullName : function (newValue) {
      if( reg.test(newValue) ) {
        alert("Invalid Name");
      }
      else {
        fullName = newValue;
      }
    },
    getFullName : function () {
     return fullName; 
    }
  }; // end of the return
}());

alert(person.getFullName());  // Jim White is printed again.

person.setFullName( 42 ); // Invalid Name; the name is not changed

It all seems logic to me, but what I haven't been able to get is how can he call either getFullName or setFullName, if these functions are in the return block.


Solution

  • There is nothing too surprising about this example; we just have to break it down.

    1. A variable called person is being declared.

    2. What kind of object is person? Well, it is the result of calling an anonymous function on zero arguments.

    3. When that anonymous function is called, it returns an object.

    4. The object returned by the function has two properties, setFullName and getFullName.

    5. The object returned by the function is the value of variable person. Therefore person.getFullName and person.setFullName are both valid expressions.

    I think the point of confusion may be that you thought the scope of getFullName and setFullName is restricted to code inside the return expression. However, JavaScript is a very dynamic language. Properties can be added to and removed from an object at any time. And it is at run time, not compile time, where the JavaScript interpreter checks for the existence of properties.