oop - Error using javascript getters & setters in IE -


i reading john resig's article javascript getters , setters when found code:

function field(val){     this._value = val; } field.prototype = {     value(){         return this._value;     },     set value(val){         this._value = val;     } }; 

i've tested , works major browsers, except damn ie, gives me script1003: ':' expected error. after wondering while, realized error happens because ie doesn't recognize javascript getters , setters, thinks get value , set value syntax error.

is there way make code cross-browser?

thanks in advance

edit:

i tried check if browser supports getters&setters:

if(window.__lookupsetter){     field.prototype = {         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 code, ie checks syntax errors, , wrongly finds these errors in get , set lines.

you can define properties without using new syntax object.defineproperty:

function field(val){     this.value = val; } object.defineproperty(field.prototype, 'value', {     get: function(){         return this._value;     },     set: function(val){         this._value = val;     } }); 

that way, code won't give syntax error in older browsers.


wrt edit, fallback code:

field.prototype = {     value: this._value }; 

will not work. this point global object - window.


the way use getters , setters cross browser not use them @ all:

field.prototype = {     getvalue: function() {         return this._value;     },     setvalue: function(val) {         this._value = val;     } }; 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -