IE 中的 JavaScript getter/setter?
无论出于何种原因,自定义对象的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
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.Resig 的帖子引用了他的 env.js 实现,这是他第一次使用您正在寻找的 getter 和 setter 方法。 这种风格对他来说效果很好的原因是因为它们没有在基于浏览器的环境中使用,env.js 主要针对服务器端 JS 或像 Rhino 这样的脚本环境。
为了处理浏览器兼容性以及关注 JavaScript 擅长的方面,请对 getter 和 setter 方法使用闭包来保护对象属性。
例如:
这将导致:
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:
Which will result in:
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/
对于旧的 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!