Error using javascript getters & setters in IE

getter-setter, internet-explorer, javascript, oop

Solution

You can define properties without using new syntax with `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, the code won't give a syntax error in older browsers.

WRT to your edit, your fallback code:

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

Will not work. `this` will point to the global object - `window`.

The only way to truly use getters and setters cross browser is not to use them at all:

Field.prototype = {
    getValue: function() {
        return this._value;
    },
    setValue: function(val) {
        this._value = val;
    }
};

Problem

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.

Original source

Related problems