Search code examples
javascriptvariablesobjectlocalinitializer

local variable in object initializers


The question is: Is it possible to create a structure like the folowing using object initializers in JavaScript?

var human = new function (years) {
    var age = years;
    Object.defineProperties(this, {
        age: {
            enumerable:true,
            get: function () {
                return age;
            },
            set: function (value) {
                if( typeof value != 'number') throw 'Age must be a number';
                age = value;
            }
        }
    });
}

What I tried to do:

var years = 0;
var human = {
    _age: years,
    get age () {
        return this._age;
    },
    set age (value) {
        if( typeof value != 'number') throw 'Age must be a number';
        this._age = value;
    }
}

This example is more intuitive and "friendly" (for me at least), but I need that "_age" was local as it is in the previous example.

Is it possible to make local variables in object initializers?


Solution

  • you can do the following:

        function myObject(){
          var privateVar = 'default';
    
          this.setPrivateVar = function(val){
            privateVar = val;
          }
    
          this.getPrivateVar= function(){
            return privateVar;
          }
    
        }
    
    var obj = new myObject();
    alert(obj.privateVar); //undefined
    alert(obj.getPrivateVar()) // default
    

    Another example:

       function myObject(){
           var privatVariable = 'default';
           return {
               getVal : function(){
                    return privatVariable;
               }
           }
       }
    
    var obj = myObject();