在 JScript 中,是否可以实现从外部看起来像对象属性的 getter 和 setter?
在尝试移植并通常使用一些非浏览器代码时,我遇到了看起来像普通对象属性的 getter 和 setter。像这样的事情:
js> var o = {
a: 4,
get b(){
return this.a + 3;
},
set b(val){
this.a = val - 3;
}
};
js> o.a
4
js> o.b
7
js> o.b=10
10
js> o.a
7
这似乎适用于最新版本的Rhino和Spidermonkey,但是是否可以在JScript(Windows Script Host)中实现或模拟该行为(定义语法对我来说不太重要)?
While trying to port and generally playing around with some non-browser code, I came across getters and setters that looked like normal object properties. Something like this:
js> var o = {
a: 4,
get b(){
return this.a + 3;
},
set b(val){
this.a = val - 3;
}
};
js> o.a
4
js> o.b
7
js> o.b=10
10
js> o.a
7
This seems to work in recent versions of Rhino and Spidermonkey, but is it possible to implement or simulate the behavior (the defining syntax is less important to me) in JScript (Windows Script Host)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
答案是
否
。 Setter 和 getter 只是像函数一样起作用的属性,但无法正确模拟语法。我有一个半途而废的概念,即使用行为来模拟 <=IE7 中 HTML 元素的 getter 和 setter,但即使如此,结果也比我最初想象的要困难。即使 IE8 也只支持 DOM 对象上的 getter/setter,而不支持 JScript 对象,所以我认为 JScript 团队需要包含这些内容(如果他们确实这样做的话)。如果有人想到在原始 JScript/ECMAScript 实现中包含 setter 和 getter 就好了。
The answer is
No
. Setters and getters are just properties that act like functions, but there is no way to emulate the syntax correctly. I had a half-way concept of emulating getters and setters on HTML elements in <=IE7 using behaviors, but even that turned out to be more difficult than I first imagined it would. Even IE8 only supports getters/setters on DOM objects and not JScript objects, so I think it's something the JScript team need to include, if they ever do.If only someone had thought to include setters and getters in the original JScript/ECMAScript implementations.
根据这篇文章(作者:jQuery 的创始人 John Resig),Javascript JScript.NET 8 支持 getter 和 setter。
According to this article (by John Resig, creator of jQuery), Javascript getters and setters are supported in JScript.NET 8.
这是浏览器及其对 getter 和 setter 的支持的完整列表。
http://robertnyman.com/javascript/#javascript-getters-setters -对象定义属性兼容性
This si a complete list of browsers and their support for getters and setters.
http://robertnyman.com/javascript/#javascript-getters-setters-object-defineproperty-compatibility