Search code examples
javascriptgetgetter

How do I "get" a member variable in JavaScript?


function User() {
    this.firstname = null;

    get getFirst() {
        return this.firstname;
    }
}

JavaScript console gives me an error saying "Unexpected Identifier" on line 12

var Jake = new User();
Jake.firstname = "Jake";
document.write(Jake.getFirst);

Solution

  • That's just not the syntax you use to define a getter. You'd use it in an object literal, like this:

    var foo = {
        get bar() {
            return 42;
        }
    };
    
    foo.bar; // 42
    

    ...but that's not where your get is.

    To define it where your get is, you'd use defineProperty:

    function User() {
        this.firstname = null;
    
        Object.defineProperty(this, "first", {
            get: function() {
                return this.firstname;
            }
        });
    }
    

    Note I called it first, not getFirst, because it's an accessor function, which looks like a direct property access, and so is traditionally not given a name in a verb form:

    var u = new User();
    u.firstname = "Paul";
    u.first; // "Paul"
    

    If you wanted to create a function called getFirst, just get rid of the get keyword:

    this.getFirst = function() {
        return firstname;
    };
    // ...
    var u = new User();
    u.firstname = "Paul";
    u.getFirst(); // "Paul"