Javascript是否有像C#这样的关键字? [英] Does Javascript have get/set keywords like C#?
问题描述
我正在使用XULRunner并在代码示例中遇到以下模式:
I'm working with XULRunner and came across the following pattern in a code sample:
var StrangeSample = {
backingStore : "",
get foo() { return this.backingStore + " "; },
set foo(val) { this.backingStore = val; },
func: function(someParam) { return this.foo + someParam; }
};
StrangeSample.foo = "rabbit";
alert(StrangeSample.func("bear"));
这导致兔熊被警告。
我以前从未见过这种在Javascript中使用过的get / set模式。它有效,但我找不到任何文档/参考。这是XUL特有的东西,最近的一种语言特征,还是我错过的东西?我很困惑,因为几个月前我一直在寻找类似的东西而找不到任何东西。
I've never seen this get/set pattern used in Javascript before. It works, but I can't find any documentation/reference for it. Is this something peculiar to XUL, a recent language feature, or just something I missed? I'm puzzled because I was specifically looking for something like this a few months ago and couldn't find anything.
作为参考,删除get或set导致语法错误。将它们重命名为其他任何内容都是语法错误。它们确实似乎是关键字。
For reference, removing "get" or "set" results in a syntax error. Renaming them to anything else is a syntax error. They really do seem to be keywords.
任何人都可以为我阐明这一点,或指向我参考?
Can anyone shed some light on this for me, or point me towards a reference?
推荐答案
正如Martinho所建议的,这里有一些链接解释JS 1.5中的getter / setter:
As suggested by Martinho, here are some links explaining the getter/setters in JS 1.5:
http://ejohn.org/blog/javascript-getters-and-setters/
http:// ajaxian.com/archives/getters-and-setters-in-javascript
请注意,IE中似乎不支持它们,一些开发人员(合法)关注具有副作用的变量赋值的想法。
Be aware though, they don't seem to be supported in IE, and some developers have (legitimate) concerns about the idea of variable assignment having side-effects.
获取/设置不是丹尼尔指出的保留关键字。创建名为get和set的顶级函数并使用上面发布的代码示例时,我没有任何问题。所以我假设解析器足够聪明,允许这样做。事实上,即使以下似乎是合法的(如果令人困惑):
get/set are not reserved keywords as Daniel points out. I had no problem creating a top-level functions called "get" and "set" and using the alongside the code-sample posted above. So I assume that the parser is smart enough to allow this. In fact, even the following seems to be legitimate (if confusing):
var Sample = {
bs : "",
get get() { return this.bs; },
set get(val) { this.bs = val; }
}
这篇关于Javascript是否有像C#这样的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!