1

https://www.w3schools.com/js/js_object_accessors.asp

On this page it is shown that a object can implement get and setters in javascript. But they use a different way to create an object than my code. How can i implement get and setters in the following code:

function Settings()
{
    var fullscreen;

    // get function
    this.fullScreen = function ()
    {
        if(fullscreen === undefined)
        {
            return false
        }
        return fullscreen;
    };


    // set function
    this.fullScreen = function (fullscrn)
    {
        fullscreen = fullscrn;
    };

    // I want to call the set like this: settingsobj.fullScreen = false;
    // I want to call the get like this: var myvar = settingsobj.fullScreen;
}
Stan
  • 629
  • 7
  • 18

1 Answers1

1

You could take an object and implement setter/getter for a wanted property.

var object = {
    fc: undefined,
    get fullscreen () { return this.fc === undefined ? false : this.fc; },
    set fullscreen (v) { this.fc = v; }
}

console.log(object.fullscreen);

object.fullscreen = 1080;

console.log(object.fullscreen);

With an instance and a provat variable and getter and setter for it.

class Settings {
    constructor() {
        var fc;
        Object.defineProperty(this, 'fullscreen', {
            get () { return fc === undefined ? false : fc; },
            set (v) { fc = v; }
        });
    }
}

var instance = new Settings;

console.log(instance.fullscreen);

instance.fullscreen = 1080;

console.log(instance.fullscreen);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392