IE 中的 JavaScript getter/setter?

发布于 2024-07-25 15:08:52 字数 223 浏览 4 评论 0原文

无论出于何种原因,自定义对象的 Javascript getters/setters 似乎适用于任何浏览器,但 IE。

IE 是否有其他非标准机制? (与许多其他功能一样)

如果没有,是否有任何解决方法可以实现相同的功能?

For whatever reason, Javascript getters/setters for custom objects seem to work with any browser but IE.

Does IE have any other non-standard mechanism for this? (As with many other features)

If not, are there any workarounds to achieve the same functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

厌味 2024-08-01 15:08:52

IE8 通过 defineProperty 拥有它,但是仅适用于 DOM 对象。 但据推测,它最终也会适用于 JavaScript 对象。

IE8 has it through defineProperty, but only for DOM objects. But supposedly, it'll eventually come for JavaScript objects as well.

爱*していゐ 2024-08-01 15:08:52

Resig 的帖子引用了他的 env.js 实现,这是他第一次使用您正在寻找的 getter 和 setter 方法。 这种风格对他来说效果很好的原因是因为它们没有在基于浏览器的环境中使用,env.js 主要针对服务器端 JS 或像 Rhino 这样的脚本环境。

为了处理浏览器兼容性以及关注 JavaScript 擅长的方面,请对 getter 和 setter 方法使用闭包来保护对象属性。

例如:

foo: function(val) {
     var bar = val;
     this.setBar: function(newBar) { 
         bar = newBar;
     },
     this.getBar: function() {
         return bar;
     }
}

这将导致:

var checkFoo = foo("cool!");
alert(checkFoo.getBar()); //cool!
checkFoo.setBar("nice!");
alert(checkFoo.getBar()); //nice!

Resig's post references his env.js implementation being the first time he uses the getters and setters methodology you are looking for. The reason this style of works fine for him is because they are not being used in a browser based environment, env.js is focused primarily for server-side JS or scripting environments like Rhino.

To handle browser compatibility as well as focusing on an aspect that JavaScript does very well, use closures for your getter and setter methods to protect object properties.

For example:

foo: function(val) {
     var bar = val;
     this.setBar: function(newBar) { 
         bar = newBar;
     },
     this.getBar: function() {
         return bar;
     }
}

Which will result in:

var checkFoo = foo("cool!");
alert(checkFoo.getBar()); //cool!
checkFoo.setBar("nice!");
alert(checkFoo.getBar()); //nice!
萌能量女王 2024-08-01 15:08:52

IE6+ 的解决方案使用 onpropertychange 事件和较新的规范 DefineProperty。 需要注意的是,您需要将变量设置为 dom 对象。

完整详细信息:

http://johndyer.name/native-browser-get -set-properties-in-javascript/

A solution for IE6+ is available that uses the onpropertychange event and the newer spec defineProperty. The slight catch is that you'll need to make your variable a dom object.

Full details:

http://johndyer.name/native-browser-get-set-properties-in-javascript/

咽泪装欢 2024-08-01 15:08:52

对于旧的 IE 浏览器,您还可以使用 VB 来模拟 getter 和 setter
看看这个
吸气剂和吸气剂 具有跨浏览器 VBClass 的所有 IE 的设置器!

For old IE browsers you can also use VB to emulate getter and setter
Take a look at this
getters & setters for all IE with cross browser VBClass!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文