Object.defineProperty for all browsers?

Shane picture Shane · Apr 23, 2012 · Viewed 12.5k times · Source

Asking about Object.defineProperty as demonstrated below:

function testComponent(){
    var testProperty;
    Object.defineProperty(this, "testProperty",
    {
        get : function()
        {
           return testProperty;
        },
        set : function(val)
        {
          testProperty = val;
        }
    });
}

Where it would be used like so:

testObject = new testComponent();
testObject.testProperty = "testValue";

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?

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


QUnit tests below: (jsFiddles)

(these pass in all browsers on my machine except IE 7 & 8

direct use of defineProperty, no shims:
http://jsfiddle.net/uSYFE/

fiddle using the ES5 shim, I'm assuming all I need to do is include it? :
http://jsfiddle.net/hyperthalamus/ntwDy/

fiddle using the IE recommended solution :
http://jsfiddle.net/hyperthalamus/xfvz3/

Answer

Florian Margaine picture Florian Margaine · Apr 23, 2012

According to ES5-shim:

/!\ Object.defineProperty

This method will silently fail to set "writable", "enumerable", and "configurable" properties.

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 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#issue/5

So you know your answer. It can be done on DOM elements, that's it (and on IE8 only).

I'd suggest you just use get/set methods if you want IE7 to work.