user2640929
user2640929

Reputation: 59

Unfamiliar syntax in javascript object

My question:


    var nsPreferences = {

    property1:"",

    get mPrefService()
        {
          return Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(Components.interfaces.nsIPrefBranch);
        },

    setBoolPref: function (aPrefName, aPrefValue)
        {
          try 
            {
              this.mPrefService.setBoolPref(aPrefName, aPrefValue);
            }
          catch(e)
            {
            }
        },

    getBoolPref: function (aPrefName, aDefVal)// Prefs.jsで使用
        {
          try
            {
              return this.mPrefService.getBoolPref(aPrefName);
            }
          catch(e)
            {
              return aDefVal != undefined ? aDefVal : null;
            }
          return null;        // quiet warnings
        },


    };

In this object nsPreferences, what is this "get mPrefService(){}"? This is the first time I've seen this kind of syntax in javascript object. Would anyone tell me about this syntax?

Upvotes: 2

Views: 85

Answers (1)

bfavaretto
bfavaretto

Reputation: 71908

It's a getter function. It will look like a variable when you read it:

var someService = nsPreferences.mPrefService;

It calls that function without using the regular invocation parens. You can also use the set operator to create a "setter" function for the same property:

set mPrefService(val){
    this.actualVal = val;
},
nsPreferences.mPrefService = "service";

Upvotes: 2

Related Questions