javascript IE8 的 Object.defineProperty 替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21175290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:17:10  来源:igfitidea点击:

Object.defineProperty alternative for IE8

javascriptjqueryjquery-pluginsinternet-explorer-8

提问by jdrm

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

给定如下 javascript 代码(从下面引用的插件中提取):

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

插件的完整代码位于: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.

从我读到的对 Object.defineProperty 的调用在 IE8 上不起作用,因为这不是 DOM 对象。

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

这是准确的吗?..如果是......重写这个getter(和setter)以符合IE8的最佳方法是什么?

回答by Alex Wayne

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

IE8 不支持非 DOM 对象属性的 getter/setter 函数。

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

这里的“解决方案”是不依赖属性 getter,而是使用完整的 getter 函数。

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

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

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

或者,不要保留this._options为“内部”变量,只需删除下划线允许直接访问。这样你就不需要魔法了。

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

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

回答by Dalorzo

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:

您可以在此处找到其余代码: