Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setter and getter in javascript, I met a error

Tags:

javascript

My English is not good, but I will try my best to explain my question simply. Description: Alert result is 1, I don't why, I think this should be 2015 to alert.

    var book = {};
    Object.defineProperties(book, {
            _year: {
                value: 1
            },
            edition: {
                value: 23
            },
            year: {
                get: function () {
                    return this._year;
                },
                set: function (newValue) {
                    if (newValue > 2004)
                        this._year = newValue;
                }
            }
        }
    );
    book.year = 2015;
    alert(book.year);
like image 860
xina1i Avatar asked Jan 08 '15 13:01

xina1i


People also ask

How do getters and setters work in JavaScript?

Getters/setters can be used as wrappers over “real” property values to gain more control over operations with them. For instance, if we want to forbid too short names for user , we can have a setter name and keep the value in a separate property _name : let user = { get name() { return this.

Can you have a setter without a getter in JavaScript?

Do you need getter and setters ? No.

What does .get do in JavaScript?

The get syntax binds an object property to a function that will be called when that property is looked up.


1 Answers

You need to add writable: true like this

_year: {
  value: 1,
  writable: true
},

for __year_.

From Mozilla Developer Network:

writable

true if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.

like image 110
Roope Hakulinen Avatar answered Oct 06 '22 23:10

Roope Hakulinen