Cross-browser Getter and Setter

前端 未结 4 547
误落风尘
误落风尘 2020-12-23 17:52

This works in modern Chrome/Firefox/Opera but fails in IE8. Haven\'t tried it in IE9. How can I make this cross-browser compatible, including IE7+? (Fiddle here.)

         


        
4条回答
  •  温柔的废话
    2020-12-23 18:31

    There is a "definePropery" method that will essentially allow you to create accessor methods (getters/setters) on Objects without the need to invoke a function call like setProp() / getProp().

    The syntax is a little weird but I've been able to get this to work on Firefox, Chrome, Safari and IE9.

    Say I have JavaScript Object called "Person".

    function Person()
    {
     // set a default value //
        this.__name = 'John';
     // add getter & setter methods //
        Object.defineProperty(this, "name", {
            get: function() {
            // additional getter logic
                return this.__name;
            },
            set: function(val) {
                this.__name = val;
            // additional setter logic
            }
        });
    }
    
    var p = new Person();
    console.log(p.name); // 'John'
    p.name = 'Stephen';
    console.log(p.name); // 'Stephen'
    

    More info on Mozilla's site here.

提交回复
热议问题