IE8的Object.defineProperty替代方案

给出如下的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 }); } 

该插件的完整代码位于: https : //github.com/MartinF/jQuery.Autosize.Input/blob/master/jquery.autosize.input.js

从我读到的内容调用Object.defineProperty将无法在IE8上运行,因为这不是DOM对象。

这是准确的吗?..如果是……这将是重写这个getter(和setter)符合IE8的最好方法吗?

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

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

 AutosizeInput.prototype.getOptions = function() { return this._options; }; var input = new AutoresizeInput(); input.getOptions(); 

或者,不要将this._options保持为“内部”变量,只需直接删除下划线允许访问。 这样你根本不需要任何魔法。

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

你可以创建自己喜欢的东西

  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 ... 

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