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
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With