适用于所有浏览器的Object.defineProperty吗? [英] Object.defineProperty for all browsers?
问题描述
询问Object.defineProperty,如下所示:
Asking about Object.defineProperty as demonstrated below:
function testComponent(){
var testProperty;
Object.defineProperty(this, "testProperty",
{
get : function()
{
return testProperty;
},
set : function(val)
{
testProperty = val;
}
});
}
将在何处使用:
testObject = new testComponent();
testObject.testProperty = "testValue";
根据我到目前为止所看到的,似乎没有跨浏览器解决方案,因为我尝试使用 这篇文章 ,而我的测试在IE 7和amp;中仍然失败. 8,谁能对此有所了解?
Based on what I've seen so far, it looks like there is no cross browser solution, as I've tried using es5-shim with no luck, but I would like to confirm. I also found a reference to this post and my tests still fail in IE 7 & 8, can anyone shed any light on this?
我记得几个月前在S/O的某个地方浏览过一个相关的问题,我想我看到有人在答案中为此写了一个解决方案. getter/setter的任何常规解决方法也将不胜感激.我的想法是,我需要在不将参数更改通过方法传递的情况下,在对象上使用某种等效的getter setter方法.我不需要IE6,但我想支持IE7 + ff 3.6+等范围内的浏览器
I remember looking through a related question a few months ago somewhere on S/O and I think I saw someone had written a solution for this in an answer. Any general workarounds for getter / setters would also be appreciated. The idea is that I need some equivalent of a getter setter on an object without passing the parameter change through a method. I don't need IE6, but I would like to support browsers in the range of IE7+ ff 3.6+ , etc
(这些密码会在我的计算机上的所有浏览器中传递,除了IE 7和8
(these pass in all browsers on my machine except IE 7 & 8
直接使用defineProperty,没有填充:
http://jsfiddle.net/uSYFE/
使用ES5填充程序进行小提琴演奏,我假设我需要做的就是包括它?:
http://jsfiddle.net/hyperthalamus/ntwDy/
使用IE推荐的解决方案:
http://jsfiddle.net/hyperthalamus/xfvz3/
推荐答案
根据 ES5-shim :
/!\ Object.defineProperty
/!\ Object.defineProperty
该方法将无声地设置为可写",可枚举"和可配置".属性.
This method will silently fail to set "writable", "enumerable", and "configurable" properties.
为"getter"或"setter"提供"get"或设置"在描述符上使用"defineGetter"的引擎将在无提示的情况下静默失败.和"defineSetter",包括到目前为止的IE 8的所有版本.
Providing a getter or setter with "get" or "set" on a descriptor will silently fail on engines that lack "defineGetter" and "defineSetter", which include all versions of IE up to version 8 so far.
IE 8提供了此方法的版本,但仅适用于DOM对象.因此,垫片将不会被安装并且尝试设置值".属性将在非DOM对象上静默失败.
IE 8 provides a version of this method but it only works on DOM objects. Thus, the shim will not get installed and attempts to set "value" properties will fail silently on non-DOM objects.
https://github.com/kriskowal/es5-shim/issues#第/5期
所以您知道您的答案.可以在DOM元素上完成(仅在IE8上).
So you know your answer. It can be done on DOM elements, that's it (and on IE8 only).
如果您希望IE7正常工作,我建议您只使用get/set方法.
I'd suggest you just use get/set methods if you want IE7 to work.
这篇关于适用于所有浏览器的Object.defineProperty吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!