How To Use Object Accessors In JavaScript With Example

admin_img Posted By Bajarangi soft , Posted On 10-10-2020

Getters and setters allow you to define Object Accessors (Computed Properties). so today we discuss about object accessor with java script

How To Use Object Accessors In JavaScript With Example

JavaScript Getter (The get Keyword)

This example uses a lang property to get the value of the language property.
Example(1)

<script>
    // Create an object:
    var person = {
        firstName: "Megha",
        lastName : "Doe",
        language : "en",
        get lang() {
            return this.language;
        }
    };

    // Display data from the object using a getter:
    document.getElementById("demo1").innerHTML = person.lang;
</script>
 

JavaScript Setter (The set Keyword)

This example uses a lang property to set the value of the language property.
Example(2)

<script>
    // Create an object:
    var person = {
        firstName: "Megha",
        lastName : "Doe",
        language : "en",
        get lang() {
            return this.language;
        }
    };

    // Set an object property using a setter:
    person.lang = "en";

    // Display data from the object:
    document.getElementById("demo2").innerHTML = person.language;
</script>
 

Differences between these two below examples

Example 3

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

    // Display data from the object using a method:
    document.getElementById("demo").innerHTML = person.fullName();
</script>

Example 4

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

    // Display data from the object using a getter:
    document.getElementById("demo").innerHTML = person.fullName;
</script>
 

Example 3 access fullName as a function: person.fullName().

Example 4 access fullName as a property: person.fullName.

The second example provides simpler syntax.
 


Data Quality

JavaScript can secure better data quality when using getters and setters.

Using the lang property, in this example, returns the value of the language property in upper case:

Example(6)
<script>
    // Create an object:
    var person = {
        firstName: "John",
        lastName : "Doe",
        language : "en",
        get lang() {
            return this.language.toUpperCase();
        }
    };

    // Display data from the object using a getter:
    document.getElementById("demo").innerHTML = person.lang;
</script>

Using the lang property, in this example, stores an upper case value in the language property:

Example(7)

<script>
    var person = {
        firstName: "John",
        lastName : "Doe",
        language : "",
        set lang(lang) {
            this.language = lang.toUpperCase();
        }
    };

    // Set an object property using a setter:
    person.lang = "en";

    // Display data from the object:
    document.getElementById("demo").innerHTML = person.language;
</script>

Why Using 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


Object.defineProperty()

The Object.defineProperty() method can also be used to add Getters and Setters:
Example(8)

<script>
    // Define an object
    var obj = {counter : 0};

    // Define Setters and Getters
    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 (value) {this.counter -= value;}
    });

    // Play with counter:
    obj.reset;
    obj.add = 5;
    obj.subtract = 1;
    obj.increment;
    obj.decrement;
    document.getElementById("demo").innerHTML = obj.counter;
</script>


Complete code for accessing objects to set and get data using java script
<!DOCTYPE html>
<html>
<head>
    <title>How To Use Object Accessors In JavaScript With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    body{
        background: black;
    }
</style>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 id="color" style="color: White">How To Use Object Accessors In JavaScript With Example</h1>
    </div>
<br>
<br>
    <div class="well">
        <h2 id="demo1"></h2>
        <h2 id="demo2"></h2>

        <script>
            // Create an object:
            var person = {
                firstName: "Megha",
                lastName : "Doe",
                language : "English",
                get lang() {
                    return this.language;
                }
            };

            // Display data from the object using a getter:
            document.getElementById("demo1").innerHTML = person.lang;

            // Set an object property using a setter:
            person.lang = "en";
            // Display data from the object:
            document.getElementById("demo2").innerHTML = person.language;
        </script>
    </div>
</div>
</body>
</html>

 

Related Post