Search code examples
javascriptjqueryinternet-explorerpermission-deniedsizzle

Overriding jQuery function loses 'this' scope


I am trying to implement the following answer from another question:

https://stackoverflow.com/a/26469105/2402594

Basically I need to add an extra check to a jQuery function. The following code is in jQuery library:

enter image description here

But I can't modify the original jQuery, so I am creating a patch in a separate file. What I am doing is overriding the find function and add functionality as follows:

(function() {
var originalFind = jQuery.fn.find;

jQuery.fn.find = function () {
    try {
        document === document;
    }
    catch (err) {
        document = window.document;
    }

    return originalFind.apply(this, arguments); 
};
})();

The function is overridden correctly, however, when the code calls 'find', my 'try' doesn't throw any exception when it should because the scope is different than the one inside the Sizzle function, so the original issue is still there.

I have also tried duplicating all of the Sizzle code, adding my modification and assigning it to jQuery.fn.find as done above, however the scope issue is still there and some crashes happen.

I need 'document' to be set before it reaches the following check or it crashes due to permission denied: enter image description here

How could I share the scope so that the try/catch can be done correctly? Is it even possible? Any other ideas?

Thank you


Solution

  • As we all known, JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.

    So, if the document is defined in the JQuery library function, I think you can't access it. You could try to define a global variable to store the document, then, you can access it in the JQuery library function and the override function.

    More details about Javascript Scope, check these links: link1 and link2