JavaScript允许getter和setter吗? [英] Does JavaScript allow getters and setters?

查看:94
本文介绍了JavaScript允许getter和setter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<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>

这种风格就像是python,

this style is like to python ,

这是我第一次看到这段代码,

this is my first time to see this code ,

你能否在javascript中给我更多关于'get'和'set'的例子。

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

谢谢

推荐答案

它可以在某些引擎中,并且它在 EcmaScript 5 ,因此将来应该更广泛地采用。 兼容性表并未直接解决此问题,但可能会遵循 defineProperties ,它提供了用于执行相同操作的API。如前所述,John Resig有一篇很好的有关新对象和属性API的文章

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允许getter和setter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆