Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create javascript property like C# property

Tags:

javascript

c#

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. In order to get the "value" property out of my widget, I've hooked up to the onchange event and I'm setting a variable everytime the value of the textarea changes.

Is there a way to accomplish this without hooking up to the onchange event.

Edit

In other words, is it possible to write something in JavaScript that behaves like getters and/or setters.

like image 867
Seattle Leonard Avatar asked Jul 08 '10 22:07

Seattle Leonard


1 Answers

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.

like image 72
Tim Down Avatar answered Sep 24 '22 00:09

Tim Down