G
So, this answer, I'm gonna try to finally exhaust this subject, which is constantly emerging at (ru)SO.#0. EvalMethod https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/eval performs the JavaScript code submitted by the line.It is clear from the definition that its use is very simple. With regard to the task, it would look like:function invokeMe() {
return "Hello world!";
}
var result = eval("invokeMe()");
console.log(result);Important distinctions eval() It is from other approaches that an expression given as a line may refer to the current context:function localContext() {
let x = 3;
let y = 4;
// eval ссылается на текущий контекст,
// так что локальные переменные x и y ему видны
return eval("x * y");
}
function globalContext() {
let x = 3;
let y = 4;
// создадим ссылку на eval
var globalEval = eval;
try {
// так как вызов не является прямым,
// то переменные x и y недоступны для eval!
return globalEval ("x * y");
} catch (e) {
// что мы и увидим благодаря этой строчке
return "Error: " + e.message;
}
}
console.log(localContext()); // 12
console.log(globalContext()); // Error: x is not definedUsing, I think it's clear.However, each of us has seen statements in the spirit of:eval() (laughs) evil)eval() - evil!Follow the list. Why does this function have such an opinion?eval() - a dangerous function that fulfils the code with all the privileges of the consignor. If you launch eval() With a line that can be influenced by malicious men, you can launch a harmful code on a user device with your web page rights. So it's not worth using this method for serious purposes. #1. FunctionWhen it comes. eval()I don't mention it. new Function()Designer https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Function creates a new object Function. In JavaScript
Each function is the object of Function.The following important differences from the past are noteworthy:Unlike eval()with help new Function() We're not just...
We do the code from the line, and we create it. full function,
similar to what we have defined through function() { } (so as a global facility Function inherited some.
Methods and properties through the prototype of the object
Function.prototypewhich may accept the input parameters and may be reused Unlike eval()the functions created by the new Function()cannot be invoked area of visibility in which they are
They were created because they only have access to the challenge.
global and its internal variables!Unlike eval()it's not the last listed in the body.
the function of the expression, or the one expressly transferred by the operator
return (yeah, or undefined♪ In general, the behaviour of the normal function, as it is / ̧(,)_/ ̧Syntaxis:new Function([arg1[, arg2[, ...argN]],] functionBody)With the theory, I think it's clear: new Function()in which the names of the formal arguments and the obligatory parameter have been transmitted, the rigid presentation of the body of the method creates, in fact, a functionWith regard to the task:// Функция с параметром
function invokeMe(name) {
return "Hello " + name + "!";
}
// Функция без параметров
function helloWorld() {
return invokeMe("world");
}
// Определим функцию, которая будет возвращать результат
// исполнения метода helloWorld()
var world = new Function("return helloWorld();");
// Определим функцию, которая будет возвращать результат
// исполнения метода invokeMe(), передавая в него параметр name
var named = new Function("name", "return invokeMe(name);");
// Определим функцию, которая будет возвращать результат
// исполнения метода invokeMe(), передавая в него
// нулевой элемент объекта arguments, который, как и в обычных
// функциях, можно использовать внутри тела функции
var named2 = new Function("return invokeMe(arguments[0]);");
// Проверим)
console.log(world()); // Hello world!
console.log(named("Vasya")); // Hello Vasya!
console.log(named2("Petya")); // Hello Petya!I think the principle of use is understandable. By the way, new Function() is considered a safer option than eval()but it should not be forgotten that a potential villain who has access to a line of function transferred in the body ' s quality can still influence the resulting code#2. Access to the facility as a container ' s properties by means of a bracketI think we all know that the object's properties can be dealt with in several ways.Simple example:let test = {
name: "Test",
sayHello: () => console.log("Hello!")
};
// Обратимся к свойству name объекта test:
// Самый очевидный вариант - сделать так:
console.log(test.name); // "Test"
// Однако мы можем сделать это и с помощью скобочной нотации:
console.log(test["name"]) // "Test"
// Теперь же вызовем внутреннюю функцию sayHello объекта test:
// И вновь самым очевидным выбором будет:
test.sayHello();
// Однако опять же нам может помочь скобочная нотация:
test"sayHello";How can this be applied to the task? I've already touched it on the top of the snipe, but let's see this case in a little more detail:// Определим глобальную функцию
function helloFromGlobal() {
console.log("Hello from outer function!");
}
// Определим объект, свойством которого будет функция
var obj = {
helloFromLocal: () => console.log("Hello from inner function!")
};
// Как же получить доступ к глобальной функции?
// Все просто, ведь контейнером для нее является объект window
// (как и для любого другого глобального объекта)
let outer = window["helloFromGlobal"];
// А как же получить доступ ко внутренней функции объекта,
// если его имя доступно нам только в качестве строки?
// Опять же, объект является глобальным, так что:
let inner = window["obj"]["helloFromLocal"];
// Проверим, что мы получили именно наши функции,
// а не кота в мешке в лице undefined:
outer(); // Hello from outer function!
inner(); // Hello from inner function!This method may be considered one of the the most appropriate In the task, the bracket and the exact note are interchangeable and their conduct is entirely https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Property_Accessors as well as through a bracket, an arrogant is unlikely to be able to launch any harmful code.Comments mentioned that it might be necessary to start a function, the to which the following is described: myObj.method.myFunc♪The answer is simple: split the line at the point and walk the whole path described by the point note by means of a bracket:
// "Путь" к функции
var func = 'myObj.method.myFunc';
// Опишем объект
var myObj = {
method: {
myFunc: () => console.log("I was here!")
}
};
// Получим "путь", разделив точечную нотацию
var path = func.split('.');
// Присвоим переменной значение "верхнего" уровня
var myFunc = window;
// Начнем спускаться глубже и глубже, пока не дойдем до функции
for (i in path)
myFunc = myFunc[path[i]];
// Проверка
myFunc(); // I was here!Dead, hearty and secure!#3. Creation of the wordAnother good option could be the way the idea was already presented at the present time. https://ru.stackoverflow.com/a/861293/248572 Participant https://ru.stackoverflow.com/users/232932/qwabra : The point is, you need to create a certain object-to-the-word, in which you can add functions and then call them by name.For example, the code was:// Определим нашу конструкцию, которая будет отвечать
// за хранение и вызов функций
var funcs = new function() {
// Хранилище
let funcs = [];
// Добавление функции в хранилище
this.push = function() {
// Добавление функции с использованием ее названия
if (arguments.length == 1 && arguments[0] && arguments[0].name)
return !!(funcs[arguments[0].name] = arguments[0]);
// Добавление функции с использованием указанного названия
else if (arguments.length == 2 && arguments[0] && arguments[1])
return !!(funcs[arguments[0]] = arguments[1]);
// Добавление не удалось
return false;
};
// Вызов функции с указанными аргументами
this.run = function(name, ...args) {
if (name && name in funcs)
return funcs[name](...args);
// Вызов не удался
return undefined;
};
// Удаление функции из хранилища
this.remove = function(name) {
if (name && name in funcs)
return delete funcs[name];
// Функции итак у нас не было)
return undefined;
};
};
// Создадим функции
// Без параметров
function helloWorld() {
console.log("Hello world!");
}
// С параметрами
function add(...args) {
var sum = 0;
for (i in args) sum += Number(args[i]);
return sum;
}
// Добавим их в хранилище
console.log(funcs.push(helloWorld)); // true
console.log(funcs.push(add)); // true
// Определим стрелочную функцию
var sub = (...args) => {
if (args.length > 0)
{
var sub = args[0] * 2;
for (i in args) sub -= args[i];
return sub;
}
return 0;
};
// Попробуем добавить стрелочную функцию в хранилище
console.log(funcs.push(sub)); // true
// Попробуем добавить безымянную функцию
console.log(funcs.push(() => console.log("Hi!"))); // false
// Попробуем теперь явно указать ее имя
console.log(funcs.push("hi", () => console.log("Hi!"))); // true
// Начнем вызов:
funcs.run("hi"); // Hi!
funcs.run("helloWorld"); // Hello world!
console.log(funcs.run("add", 10, 3)); // 13
console.log(funcs.run("sub", 10, 3)); // 7
// Удалим функцию helloWorld из хранилища
console.log(funcs.remove("helloWorld")); // true
// Вызов удаленной функции невозможен
console.log(funcs.run("helloWorld")); // undefinedThis design allows Add. functions, Call by name (possible even with parameters) and - Delete From the vault. OutcomesIn this response, I have sought to consider the most common ways of challenging functions (locations - not only) with only a line with their name.I would like to draw your attention to the fact that they are located in order to increase their usage. Starting unwanted eval() and finishing its structure to the necessary needs.The question of recommendations, of course, may be controversial, as taste and colour are said. ♪ ♪If you think that my answer was incorrectly overwhelmed by some very good method of solving the problem, write in the comments, I would be happy to add the answer!