jquery static method Globaleval use and source code analysis

Source: Internet
Author: User

The Eval function is familiar to everyone, but the Globaleval method is seldom used, and most reference manuals do not have the relevant API, the following is the usage and the source of the corresponding description:

jQuery.globalEval()function is used to globally execute a piece of JavaScript code.

Example:

var name = "global variable"; function Test () {    var name = "local variable";        alert (name);                      // Local Variables          "alert (name);");          // Local Variables          "alert (name);");  // Global Variables }test ();

You can see that this method has a scope difference that is always under the global scope compared to the Eval method, and the following is the source code analysis:

//evaluates a script in a global context//workarounds based on findings by Jim Driscoll//Http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-contextGlobaleval:function(data) {if(Data &&rnotwhite.test (data)) {         //We use ExecScript on Internet Explorer         //We Use a anonymous function So, context is window         //rather than jQuery in Firefox(Window.execscript | |function(data) {window["Eval"].call (window, data);     }) (data); } },

Note in the meaning of this method is mentioned in the implementation is on the basis of Jim Driscoll and the relevant article link also attached to the above, simply link can also open the look, the inside roughly introduced how to let JS code in the global execution method, For IE, it provides a less common method (I heard it for the first time anyway)---window.execscript

The Window.execscript method executes a script code based on the provided scripting language. The Window.execscript method has two parameters, the first parameter specifies the script snippet to be executed, the second parameter specifies the scripting code language category (the default is JScript), and the code after the ExecScript method executes is under the global scope. Example:

var str= ' Global ';     (function() {        var str= ' local ';        Window.execscript (' alert (str) ');  // IE Global } ());  

However, this method is now only IE support, the earlier version of Chrome support has now been abandoned, the specific method of this introduction please refer to http://ued.sina.com/?p=789;

Open the note in the URL is an English-language website four English water products I do not hesitate to use the Google Web translation features, Google can not give the force to tell me can't translate, that no way can only bite the bullet to read, afraid to translate the original attached please the original text to prevail

for more standards-respecting browsers, the "the-do"-should be- Ction, which is a standard function attached to every function object. So, eval. (window, src )  should work. But to understand why, it's important to know on context, in addition to scope. Every function call has it's own context:this is the object that's represented by the special value  this . When we use the "Call function", the first parameter is the context object we'll use for  this . This was handy for all kinds of purposes, but for us, it's just nice to the set the context to the  window & Nbsp;object-which, you ' ll recall, is the global.

This paragraph is to provide a workaround, for standard browsers can use the Eval function to parse the JS code string, and then through the way the object impersonating the scope of the window, the following is their own test:

var str= ' Global '; (function() {     var str= ' local ';      Alert (str) "); }());  

After testing IE9 and above and non-ie are pop-up "global", IE9 the following pop-up parts, this method has to see compatibility problems ah, but this method is intended for non-ie use, you ie love how to

Sadly,eval.call(window,src)Breaks on chrome-it complains for contexts not matching. Odd-and I was unable to Google up what this might is so. But a couple lucky guesses later, and I discovered thatwindow.eval.call(window,src)Works on all Non-ie browsers. Now, when I say "var j = 1", the window[j] was the variable that ' s set ... So, that's good. Why does we have to add the extrawindow.On Chrome? Not sure-i could guess, but it's too likely to be wrong.

The author used a number of "odd", I also feel very "odd", the author said in Google Error, and then change the Code to window. Eval. Call (window,src) OK, as the author is puzzled, the global approach is not required to add window directly calls this everyone is clear, but I do the test is not a problem, it should be the age of the old Google has solved, and finally the author also mentions that Firefox has problems in performing parsing this

At this point, I thought we ' d licked the problem. No such luck. Sure, global variables is getting set, but it turns out so if you Say:alert (this)-then you would correctly receive T He global object back in Chrome and Safari, but not firefox-there, you ' d get back the object that is the enclosing obje CT before the call function got called. Very odd, and likely a bug in their implementation.

Now that the global resolution alert (this) is definitely window only, and Firefox pops up the nearest action chain object, for the need to test the code below:

var str= ' Global ';       (function() {           var str= ' local ';            Alert (This) ");   ());  

The detection of Firefox is not a problem, it is estimated that Firefox also early to deal with this problem, in the article's last author left a method

var function Globaleval (src) {    if  (window.execscript) {        window.execscript (src);         return ;    }     var function () {        window.eval.call (WINDOW,SRC);    };    fn ();};

You can say this is enough, but looking back at our jquery source will find a lot leaner.

Data && rnotwhite.test (data)

This condition guarantees data and is not a space, of course, you can not pass the string but it doesn't make sense. Rnotwhite is defined in the constructor

// Check If a string has a non-whitespace character in it    Rnotwhite =/\s/,

As to why the detection can not have spaces or in this foreign language there are other developers pointed out if it is blank in the IE8 error

by Vesperaba-2012-10-18 08:54If src is a blank string you'll get an errorinchIE8. To avoid this added the following check at the beginning:if(src = = Undefined | | src = = ") {return;} The wholefunctionWould be :varGlobaleval =functionGlobaleval (src) {if(src = = Undefined | | src = = ") {return;}if(window.execscript) {window.execscript (src);return; }varfn =function() {window.eval.call (WINDOW,SRC);   }; fn ();};

Logic or operation to choose which way to parse, if the use of Eval is in a self-executing anonymous function, the structure is very thin

function (data) {      "eval" ].call (window, data);}) (data);

Another thing to be aware of is that the method has no return value, or it can be understood to return undefined

jquery static method Globaleval use and source code analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.