Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

xulrunner - Does Javascript have get/set keywords like C#?

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"));

This results in "rabbit bear" being alerted.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...