Javascript prototype syntax - variable name starting with underscore

74 Views Asked by At

I am following an online tutorial and coming across a bit of javascript code which I'm having a tough time understanding. There is a function called Note() defined in javascript. Below is the code for adding getters and setters in the the prototype section. I don't understand why the variable _id has underscore in front of it? What's the purpose of the underscore and when is it used?

Note.prototype = {
    get id() {
        if (!("_id" in this))
            this._id = 0;
        return this._id;
    },

    set id(x) {
        this._id = x;
    },

    get text() {
        return this.editField.innerHTML;
    },

    set text(x) {
        this.editField.innerHTML = x;
    }
1

There are 1 best solutions below

5
On

I narrowed down the issues and I reposted this question.

It turns out that 'name' and '_name' are two completely separate variables. If we use 'name' in the setters and getters it results in an infinite recursive call of the function which is why it doesn't work properly.

You can find the repost of this question with additional information here.

Javascript getters and setters - recursion issue