Reputation: 66637
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
Upvotes: 9
Views: 4030
Reputation: 245389
Javascript does in fact support getters and setters now. John Resig has a good blog post about them here.
John's article does a good job at mentioning several different ways of defining getters/setters on Javascript objects, but doesn't do a good job at describing when each method is applicable. I believe that is much more effectively accomplished in a more recent blog post by Robert Nyman:
Getters and setters with JavaScript
(this article also introduces the ECMAScript Standard Object.defineProperty
)
Upvotes: 3
Reputation: 78242
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"
Upvotes: 10
Reputation: 4447
It can in certain engines, and it's in the spec for EcmaScript 5, so it should be more widely adopted in the future. The Compatibility Table doesn't direclty address this, but it will likely follow defineProperties
, which provides an API for doing the same thing. As pointed out previously, John Resig has a nice article on the new object and property APIs.
Upvotes: 6
Reputation: 816232
Yes it can. Here is a nice post about it from John Resig, the creator of jQuery:
JavaScript Getters and Setters
Upvotes: 0