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?
IE8 supports getters and setters on DOM nodes, so if you really want to have getters and setters, you can do this:
Note this gives you a somewhat significant performance hit, so I wouldn't use this technique if you need to create thousands of objects like this. But if you're not worried about performance of this particular object, it'll tide you over. And if you couldn't care less about ie8 performance, and just want it to work, use this technique for ie8 only and you're golden : )
Check it on http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/
You can find the test cases on the same site at http://robertnyman.com/javascript/javascript-getters-setters.html#object-defineproperty
Result:
Change it completely. For example, instead of using accessor properties, use a combination of normal properties and functions:
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: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.You cannot (as Andy answered)
The closest alternative would be
Demo at http://jsfiddle.net/gaby/WYjqB/2/