Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

1 Answers

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"
like image 143
T.J. Crowder Avatar answered Aug 29 '26 16:08

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!