Create javascript property like C# property

后端 未结 2 376
醉梦人生
醉梦人生 2021-02-05 21:20

Is it possible to create a property on a javascript object that behaves similar to a property in C#.

Example: I\'ve created an auto-sizing textarea widget using dojo. I

2条回答
  •  鱼传尺愫
    2021-02-05 21:58

    It is possible in ECMAScript 5 implementations, which include recent versions of all major browsers. The ECMAScript 5 spec adds standardized getters and setters. One quirk is that IE 8 has this feature, but only on DOM nodes. This is what the syntax looks like:

    var obj = {};
    
    Object.defineProperty(obj, "value", {
        get: function () {
            return this.val;
        },
        set: function(val) {
            this.val = val;
        }
    });
    

    There has also been a proprietary implementation of getters and setters in Mozilla for a long time that was also later adopted by WebKit and Opera but this is not available in IE.

提交回复
热议问题