User Tools

Site Tools


javascript_getters_and_setters

Javascript Getters and Setters

from https://www.w3schools.com/js/js_object_accessors.asp

*Note: Getters and Setters are not supported in Internet Explorer 8 or earlier

Why Use Getters and Setters?

It gives simpler syntax

It allows equal syntax for properties and methods

It can secure better data quality

It is useful for doing things behind-the-scenes

Syntax

These two examples do exactly the same thing, but the second example uses a getter, so that when you call a function, it looks like you're just accessing a variable. As a bonus, a setter is provided to change the the value of the variable.

var person = {
    firstName: "John",
    lastName : "Doe",
    fullName : function() {
        return this.firstName + " " + this.lastName;
    }
};

// Display data from the object using a method:
alert(person.fullName());
var person = {
    firstName: "John",
    lastName : "Doe",
    get fullName() {
        return this.firstName + " " + this.lastName;
    },
    set fullName(str) {
        var nameParts = str.split(" ");
        this.firstName=nameParts[0];
        this.lastName=nameParts[1];
    }
};

// Change the name to something else
// give a string that contains a space, or this will give an error
person.fullName="Michael Jackson";

// Display data from the object using a getter:
alert(person.fullName);

A more advanced example

var obj = {
    counter : 0,
    get reset() {
      this.counter = 0;
    },
    get increment() {
      this.counter++;
    },
    get decrement() {
      this.counter--;
    },
    set add(value) {
      this.counter += value;
    },
    set subtract(value) {
      this.counter -= value;
    }
};
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Alternate syntax

// Define object
var obj = {counter : 0};

// Define setters
Object.defineProperty(obj, "reset", {
    get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
    get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
    get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
    set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
    set : function (i) {this.counter += i;}
});

// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
javascript_getters_and_setters.txt · Last modified: 2018/09/07 12:47 by admin