Because the Bootstrap-table plug-in needs to support the Data-name= "functionname" approach, the Eval method is used in the implementation process. We know that in JavaScript, Eval is ugly, as mentioned in MDN:
Obsolete
This feature is obsolete. Although it may still work in some browsers, the IT use is discouraged since it could to be removed to the. Try to avoid using it.
We execute string code through eval, for example:
The code is as follows |
Copy Code |
Eval ("var x = ' Hello from eval! ';"); Console.log (x);
|
However, Eval can bring some unexpected problems:
Security issues: Your string may be injected with other commands or third-party scripts.
Debugging problems: It is difficult to debug error messages.
Compression problem: The program does not minimize the string compression.
Unfortunately, in real-world development, Eval is often abused, such as parsing a JSON string, and although using eval works, we should try to avoid using it, such as using the Json.parse method.
So how do we invoke JavaScript through strings without the eval method?
First, if we have a method of string names:
The code is as follows |
Copy Code |
function we want to run var func = ' Runme '; function Runme () { Do something } |
A good solution is that we can check it by using the Window object before invoking the method:
The code is as follows |
Copy Code |
Find function var fn = Window[func]; Runme is a function? if (typeof fn = = ' function ') { FN (); } |
More often, our approach is to have a series of parameters, such as we put into the array, which we simply need to execute the Apply method:
The code is as follows |
Copy Code |
function name and parameters to pass var func = ' Runme '; var args = [1, 2, 3]; Find function var fn = Window[func]; Runme is a function? if (typeof fn = = ' function ') { Fn.apply (null, args); } |
Here, we know that invoking JavaScript through strings without eval is a safer, easier way to debug and run faster.
Finally, it encapsulates it as a tool function:
The code is as follows |
Copy Code |
var calculatefunctionvalue = function (func, args, defaultvalue) { if (typeof func = = ' String ') { //support OBJ.FUNC1.FUNC2 var fs = Func.split ('. '); if (Fs.length > 1) { func = window; $.each (FS, function (I, f) { func = func[f]; }); } else { func = Window[func]; } } if (typeof func = = = ' function ') { return Func.apply (null, args); } return defaultvalue; }; |