Get Set Accessors in Javascript

Hi,

I was wondering if anyone knew how to implement get/set accessors in Javascript. I have tried a lot of online suggestions that just dont work. For instance in C# it would be

int i
{
      get {};
      set {};
}
adavirAsked:
Who is Participating?
 
Göran AnderssonConnect With a Mentor Commented:
You can't, it's no in the language. In languages that doesn't have properties, usually a get and set method is used:

var i;

function get_i() { return i;}

function set_i(value) { i = value; }

If you for example look at Javascript code in commercial products like Microsoft ASP.NET and Telerik, they use this pattern.
0
 
KiasChaos83Commented:
You could do:

var external = function() {
      var internal;
      get: function() { return internal; };
      set: function(value) { internal = value; };
}();

And then you use it like this:

external.set('hello');
alert(external.get() + ' world');

This way, no one can directly get at the variable "internal".
0
All Courses

From novice to tech pro — start learning today.