简体   繁体   中英

Can I override prototype functions in IE8?

I have written following code to alert messages when Node.prototype.appendChild(obj) is called.

var _appendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function(object){
    alert("append");
    return _appendChild.apply(this,[object]);           ;
};  

And it does not work in IE8..

I have read this link in which the answer said prototype functions can't be overridden in IE

How do I override javascript's cloneNode?

But I still want to ask if there is any work around to do what I want.

Thanks

You cannot extend Node in IE8, but you can extend HTMLDocument.prototype and Element.prototype.

A link to Microsoft's documentation

function _MS_HTML5_getElementsByClassName(classList){
    var tokens= classList.split(" ");
    var staticNodeList= this.querySelectorAll("." + tokens[0]);
    for(var i= 1; i<tokens.length; i++){
        var tempList= this.querySelectorAll("." + tokens[i]);           
        var resultList= new Array();
        for(var finalIter= 0; finalIter<staticNodeList.length; finalIter++){
            var found= false;
            for(var tempIter= 0; tempIter<tempList.length; tempIter++){
                if(staticNodeList[finalIter]== tempList[tempIter]){
                    found= true;
                    break;                      
                }
            }
            if(found){
                resultList.push(staticNodeList[finalIter]);
            }
        }
        staticNodeList= resultList;
    }
    return staticNodeList;
}

if(!document.getElementsByClassName && Element.prototype){
    HTMLDocument.prototype.getElementsByClassName= _MS_HTML5_getElementsByClassName;
    Element.prototype.getElementsByClassName= _MS_HTML5_getElementsByClassName;
}

Thanks kennebec

Finally I found I could not implement it just because it was running in quirks mode... I wrote an example in which somebody else may be interested .

var elementPrototype = typeof HTMLElement !== "undefined"
        ? HTMLElement.prototype : Element.prototype;

var _appendChild = elementPrototype.appendChild; 

elementPrototype.appendChild = function(content){
    //Do what you want-----

    alert("Append Child!");

    //---------------------
    return _appendChild(content);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM