Вопрос

I’d like to extend the prototype of my custom constructor function with $.extend. The extender object contains a custom toString method that will not be enumerable in IE (8?). I didn’t find out whether jQuery fixes this problem internally or not.

var myConstructor = function() { /* ... */ };

$.extend(myConstructor.prototype, {
    toString: function() { return "foo"; }
});

Will this work? And if not: Is there a quick fix or do I need to use my own for-in loop?

Это было полезно?

Решение

I had the chance to test it myself and jQuery does not. Here is a solution I found:

var extendPrototype = function() {
    var objectPrototype = Object.prototype,
        hasOwnProperty = objectPrototype.hasOwnProperty,
        isBuggy = !{valueOf: 0}.propertyIsEnumerable("valueOf"),
        keys;

    if(isBuggy)
        keys = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");

    return function(prototype, object) {
        var i,
            key;

        for(key in object)
            if(hasOwnProperty.call(object, key))
                prototype[key] = object[key];

        if(isBuggy) {
            i = 0;

            for(i; key = keys[i]; i ++)
                if(object[key] !== objectPrototype[key] || hasOwnProperty.call(object, key))
                    prototype[key] = object[key]
        }

        return prototype
    }
}();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top