Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript allow getters and setters?

this is my code:

<script type="text/javascript">
var Note=function(){}
Note.prototype = {
    get id()
    {
        if (!("_id" in this))
            this._id = 0;
        return this._id;
    },

    set id(x)
    {
        this._id = x;
    }
}

var a=new Note()
alert(a.id)
</script>

this style is like to python ,

this is my first time to see this code ,

and can you give me more example about 'get' and 'set' in javascript .

thanks

like image 954
zjm1126 Avatar asked Aug 02 '10 00:08

zjm1126


1 Answers

Yes it does. This feature was added in ECMAScript 5.

PropertyAssignment:
    PropertyName : AssignmentExpression 
    get PropertyName() { FunctionBody } 
    set PropertyName( PropertySetParameterList ) { FunctionBody } 

Here are a few things to remember when using this syntax.

  1. If your object literal has a value property it cannot have getter or setter and vice versa.
  2. Your object literal cannot have more than one getter or setter with the same name.

A better way to actually use this feature is through the Object.defineProperty function.

function Person(fName, lName) {
    var _name = fName + " " + lName;
    Object.defineProperty(this, "name", { 
        configurable: false, // Immutable properties!
        get: function() { return _name; } 
    });
}

This allows you to have nice clean objects with encapsulation.

var matt = new Person("Matt", "Richards");
console.log(matt.name);  // Prints "Matt Richards"
like image 138
ChaosPandion Avatar answered Oct 03 '22 03:10

ChaosPandion