How to “properly” create a custom object in JavaScript?

后端 未结 15 1965
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  盖世英雄少女心
    2020-11-21 08:34

    In addition to the accepted answer from 2009. If you can can target modern browsers, one can make use of the Object.defineProperty.

    The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object. Source: Mozilla

    var Foo = (function () {
        function Foo() {
            this._bar = false;
        }
        Object.defineProperty(Foo.prototype, "bar", {
            get: function () {
                return this._bar;
            },
            set: function (theBar) {
                this._bar = theBar;
            },
            enumerable: true,
            configurable: true
        });
        Foo.prototype.toTest = function () {
            alert("my value is " + this.bar);
        };
        return Foo;
    }());
    
    // test instance
    var test = new Foo();
    test.bar = true;
    test.toTest();
    

    To see a desktop and mobile compatibility list, see Mozilla's Browser Compatibility list. Yes, IE9+ supports it as well as Safari mobile.

提交回复
热议问题