Object.defineProperty alternative for IE8

2019-01-24 11:27发布

Given javascript code like the following (extracted from a plugin referenced below):

var AutosizeInput = (function () {
    function AutosizeInput(input, options) {
        var _this = this;
        this._input = $(input);
        this._options = options;


    }
    Object.defineProperty(AutosizeInput.prototype, "options", {
        get: function () {
            return this._options;
        },
        enumerable: true,
        configurable: true
    });
}

Full code of the plugin located at: https://github.com/MartinF/jQuery.Autosize.Input/blob/master/jquery.autosize.input.js

From what I read the call to Object.defineProperty will not work on IE8 as this is not a DOM object.

Is that accurate?..and if it is...which would be the best way to rewrite this getters (and setters) to be IE8 compliant?

2条回答
Evening l夕情丶
2楼-- · 2019-01-24 11:46

You can create your own something like

 if (!Object.defineProperty) {
            Object.defineProperty = function (obj, prop, descriptor) {
                if (arguments.length < 3) { // all arguments required
                    throw new TypeError("Arguments not optional");
                }

                prop += ""; // convert prop to string
                ...     

You can find the rest of the code here:

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-24 11:48

IE8 does not support getter/setter functions on properties of non DOM objects.

The "solution" here is to not rely on property getters, and use a full getter function instead.

AutosizeInput.prototype.getOptions = function() {
  return this._options;
};

var input = new AutoresizeInput();
input.getOptions();

Or, instead of keeping this._options as an "internal" variable, just drop the underscore allow access directly. This way you need no magic at all.

var AutoresizeInput = function() {
  this.options = {};
}

var input = new AutoresizeInput();
input.options();
查看更多
登录 后发表回答