I was reading John Resig’s article about JavaScript Getters and Setters when I found this code:
function Field(val){
this._value = val;
}
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
I’ve tested and it works perfectly with all major browsers, except the damn IE, which gives me the SCRIPT1003: ':' expected error. After wondering for a while, I realized that this error happens because IE doesn’t recognize JavaScript Getters and Setters, so I thinks that get value and set value are a syntax error.
Is there any way to make this code cross-browser?
Thanks in advance
EDIT:
I also tried to check if the browser supports getters&setters:
if(window.__lookupSetter){
Field.prototype = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
};
}else{
Field.prototype = {
value: function(val){
if(val)
return this._value = val;
return this._value;
}
};
}
But before executing the code, IE checks for syntax errors, and it wrongly finds these errors in the get and set lines.
You can define properties without using new syntax with
Object.defineProperty:That way, the code won’t give a syntax error in older browsers.
WRT to your edit, your fallback code:
Will not work.
thiswill point to the global object –window.The only way to truly use getters and setters cross browser is not to use them at all: