Object.defineProperty polyfill [英] Object.defineProperty polyfill

查看:191
本文介绍了Object.defineProperty polyfill的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写基于ES5中新功能的JavaScript API。它相当广泛地使用 Object.defineProperty 。我将其包装为两个新函数,分别为 Object.createGetSetProperty Object.createValueProperty

I am currently writing a JavaScript API which is based on new features in ES5. It uses Object.defineProperty quite extensively. I have wrapped this into two new functions, called Object.createGetSetProperty and Object.createValueProperty

但是我在较旧的浏览器(例如可怕的IE8)中运行时遇到问题

I am however experiencing problems running this in older browsers (such as the dreaded, IE8)

请考虑以下代码:

Object.createGetSetProperty = function (object, property, get, set, enumerable, configurable) {
    if (!Object.defineProperty) throw new Error("Object.defineProperty is not supported on this platform");
    Object.defineProperty(object, property, {
        get: get,
        set: set,
        enumerable: enumerable || true,
        configurable: configurable || false
    });
};

Object.createValueProperty = function (object, property, value, enumerable, configurable, writable) {
    if (!Object.defineProperty) {
        object[property] = value;
    } else {
        Object.defineProperty(object, property, {
            value: value,
            enumerable: enumerable || true,
            configurable: configurable || false,
            writable: writable || false
        });
    }
};

如您所见,Object.createValueProperty下有一个优美的后备,但我不知道

As you can see, there is a graceful fallback under Object.createValueProperty, but I've no idea how to fallback gracefully with Object.createGetSetProperty.

有人知道任何解决方案,垫片,填充物吗?

Does anyone know of any solutions, shims, polyfills for this?

推荐答案

为清楚起见,您可能希望使用标准术语并为例程命名 defineDataProperty defineAccessorProperty

For clarity, you might want to stick with standard terminology and name your routines defineDataProperty and defineAccessorProperty.

另外,您的可枚举:可枚举|| true 的结果将是 true 的值,即使调用者传递的是false ...

Also, your enumerable: enumerable || true is going to result in a value of true even if the caller passes in false...

无论如何,要解决手头的问题:您无法在IE8中做到这一点。据说 defineProperty 在IE8中有效,但仅适用于DOM对象。 IE7及以下版本存在一些丑陋的骇客,涉及在DOM对象上使用 onpropertychanged 事件。所有这些都在其他问题中进行了详细介绍,例如 Cross-browser Getter和Setter IE8中的JavaScript getter支持以及许多其他功能。

Anyway, to get down to the question at hand: you can't do this in IE8. It is said that defineProperty works in IE8 but only on DOM objects. There are ugly hacks for IE7 and below involving using the onpropertychanged event on DOM objects. All of this has been gone over in some detail in other questions, such as Cross-browser Getter and Setter, JavaScript getter support in IE8, and many others.

这篇关于Object.defineProperty polyfill的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆