开发者

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


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"


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.


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)


Yes it can. Here is a nice post about it from John Resig, the creator of jQuery:

JavaScript Getters and Setters

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜