JavaScript getter support in IE8

Saeed Neamati picture Saeed Neamati · Oct 17, 2011 · Viewed 11.2k times · Source

Check out this code. This is a very simple JavaScript object which is implemented using Module Pattern (and you can see the live example at this fiddle address)

var human = function() {
    var _firstName = '';
    var _lastName = ''
    return {
        get firstName() {
            return _firstName;
        }, get lastName() {
            return _lastName;
        }, set firstName(name) {
            _firstName = name;
        }, set lastName(name) {
            _lastName = name;
        }, get fullName() {
            return _firstName + ' ' + _lastName;
        }
    }
}();
human.firstName = 'Saeed';
human.lastName = 'Neamati';
alert(human.fullName);

However, IE8 doesn't support JavaScript get and set keywords. You can both test it and see MDN.

What should I do to make this script compatible with IE8 too?

Answer

Andy E picture Andy E · Oct 17, 2011

What should I do to make this script compatible with IE8 too?

Change it completely. For example, instead of using accessor properties, use a combination of normal properties and functions:

human.firstName = 'Saeed';
human.lastName  = 'Neamati';
alert(human.getFullName());

Somebody else suggested using a DOM object in IE and adding the properties using Object.defineProperty(). While it may work, I'd highly recommend against this approach for several reasons, an example being that the code you write may not be compatible in all browsers:

var human = document.createElement('div');
Object.defineProperty(human, 'firstName', { ... });
Object.defineProperty(human, 'lastName',  { ... });
Object.defineProperty(human, 'children',  { value: 2 });

alert(human.children);
//-> "[object HTMLCollection]", not 2

This is true of at least Chrome. Either way it's safer and easier to write code that works across all the browsers you want to support. Any convenience you gain from being able to write code to take advantage of getters and setters has been lost on the extra code you wrote specifically targeting Internet Explorer 8.

This is, of course, in addition to the reduction in performance, the fact that you will not be able to use a for...in loop on the object and the potential confusion ensuing when you use a property you thought you defined but was pre-existing on the DOM object.