Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

javascript - Object.defineProperty polyfill

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

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

Consider the following code:

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
        });
    }
};

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...