Tech Junkie Blog: JavaScript Objects Deep Dive: Object Property Setters and Getters

Friday, December 15, 2017

JavaScript Objects Deep Dive: Object Property Setters and Getters

Most people don't realize JavaScript has object property setters and getters or accessor methods.  When an object has a setter only it is a write only property, when it has a getter only method that it is a read only property.  If a property has both then it is a read/write property.  A perfect example is if you are working with a private property in JavaScript which has the $ prefix in front of it.

Let's say you have an object with a private property $n like the example below:


        var game = {

            $n: "Awesome Game!",

            get name() { return this.$n}
        };

The code above only has a getter name that exposes the private property $n when you console.log you should get value of the $n like the code snippet below

   console.log(game.name);

  As you can see the output is as expected, it prints out the value of $n the private property because we have a getter method name()  things get interesting when we try to assign a value to name.  Its a bit confusing because we access the name method with a dot notation, the same as how we would access a property.



So if type the code below:

game.name = "Not Awesome Game!";

console.log(game.name);

What do you think the output will be?

"Awesome Game!" or "Not Awesome Game!"

If you guess "Awesome Game!" then you are correct because the $n property only has a getter method and its read only.  Even though we assign a new value to the property there's no setter method therefore, the new value is not assigned to the $n property.

However, if we change the object definition to the code below with the setter method the $n property would be changed to "Not Awesome Game!"





        var game = {

            $n: "Awesome Game!",

            get name() { return this.$n },
            set name(newName) {
                this.$n = newName;
            }
        };


Now if type

game.name = "Not Awesome Game!";

console.log(game.name);

We will get a different result:








The complete code for this post looks like the following:


        var game = {

            $n: "Awesome Game!",

            get name() { return this.$n },
            set name(newName) {
                this.$n = newName;
            }
        };

        console.log(game.name);
        game.name = "Not Awesome Game!";
        console.log(game.name);


3 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete