Implementing setter and getter in a JavaScript object

I want to implement setter and getter in local javascript. Here is an example function:

function someThing() {
   var someLocalvariable = '';
}

// with this function I want to 
// return value of someLocalvariable
// also if it is possible to implement
// setter in this way. 
someThing.prototype.getLocalVar = function() {

}

I want the variable to be "real." I'm not used to using something like this: someThing.prototype.someLocalvariable =

or

function someThing() {
   this.someLocalvariable = '';
}

or attach a function inside someThing () as follows:

function someThing() {
      var someLocalvariable = '';
   this.getLocalvariable = function() {
      return someLocalvariable;
   }
}

I would really appreciate any advice and help.

+5
source share
7 answers

, , ( ), ( ), , , , , ().

, , . , . . "" .

(, , , , ):

function SomeThing() {
    var privateVar;

    this.setPrivateVar = function(val) {
        privateVar = val;
    };
    this.getPrivateVar = function() {
        return privateVar;
    };
}

// use:
var t = new Something();
t.setPrivateVar("foo");
console.log(t.getPrivateVar()); // "foo"

, .

: , SomeThing, . . , SomeThing, . , , , . ( , , , / - , .)

: - ( , ), , , , , . , id, , ):

var SomeThing = (function() {
    var cache = {}, idAllocator = 0;

    function SomeThing() {
        this.id = ++idAllocator; // The unique identifier, can be a string if desired
        cache[this.id] = {};
    }
    SomeThing.prototype.getPrivateVar = function() {
        var data = cache[this.id];
        return data && data.privateVar;
    };
    SomeThing.prototype.setPrivateVar = function(value) {
        cache[this.id].privateVar = value;
    };
    SomeThing.prototype.destroy = function() {
        delete cache[this.id];
    };

    return SomeThing;
})();

: cache . , , , . , destroy ( ), cache, id.

:

  • , (id )
  • , SomeThing , destroy , . , JavaScript, , , cache .
  • ( ). , id , , . JavaScript , , .

, , SomeThing , , .


: , SomeThing SomeThing. JavaScript , , (, new), . SomeThing new, . , , , (Date , setHours ).

+13

- :

function Field(val){
    var value = val;

    this.getValue = function(){
        return value;
    };

    this.setValue = function(val){
        value = val;
    };
}
var field = new Field("test");
field.value
// => undefined
field.setValue("test2")
field.getValue()

ref: http://ejohn.org/blog/javascript-getters-and-setters/

+3

JavaScript

+2

. someThing(), , , ( , ?). - , ?

+2

Object.defineProperty() , getter setter ..

( ), Closure, .

getter setter temperature, "private" var temperature.

var temperature / Archiver(), .

, ES5 Object.defineProperty(), ES3.

function Archiver() {
    var temperature = null;
    var archive = [];

    Object.defineProperty(this, 'temperature', {
        get: function () {
            console.log('get!');
            return temperature;
        },
        set: function (value) {
            temperature = value;
            archive.push({ val: temperature });
        }
    });

    this.getArchive = function () {
        return archive;
    };
}

var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]
+2

getter

var address = {

            street : "No street",
            city : "No city",
            state : "No state",     

            get getAddress()
            {
                return (this.street+","+this.city+","+this.state);
            },

            set setAddress(theAddress)
            {
                var part = theAddress.toString().split(", ");
                this.street = part[0] || "";
                this.city = part[1] || "";
                this.state = part[2] || "";
            }
        };


        address.setAddress = "27 Sus Road, Pune, MH";
        console.log(address.getAddress);


        //Other setter and getter

        function Square(side)
        {
            this._side = side;


        };

        Square.prototype = {

            set setSide(side){ 
                this._side = side;
            },

            get getSide(){ 
                return this._side;
            },

            get getArea(){ 
                return (this._side * this._side);
            }               
        };


        var mySquare = new Square(10);

        mySquare.setSide = 15;

        console.log("Area of square is "+mySquare.getArea+" with side "+mySquare.getSide);
0
source

First method

var address = {

            street : "No street",
            city : "No city",
            state : "No state",     

            get getAddress()
            {
                return (this.street+","+this.city+","+this.state);
            },

            set setAddress(theAddress)
            {
                var part = theAddress.toString().split(", ");
                this.street = part[0] || "";
                this.city = part[1] || "";
                this.state = part[2] || "";
            }
        };


        address.setAddress = "27 Sus Road, Pune, MH";
        console.log(address.getAddress);

Second method

function Square(side)
        {
            this._side = side;


        };

        Square.prototype = {

            set setSide(side){ 
                this._side = side;
            },

            get getSide(){ 
                return this._side;
            },

            get getArea(){ 
                return (this._side * this._side);
            }               
        };


        var mySquare = new Square(10);

        mySquare.setSide = 15;

        console.log("Area of square is "+mySquare.getArea+" with side "+mySquare.getSide);
0
source

All Articles