Eval в js что это

от admin

Eval в js что это

Предупреждение: Выполнение кода JavaScript с текстовой строки — это невероятный риск для безопасности. Злоумышленнику слишком легко запустить какой угодно код, когда вы используете eval() . Смотрите Никогда не используйте eval()!, ниже.

Метод eval() выполняет JavaScript-код, представленный строкой.

Интерактивный пример

Синтаксис

Параметры

Строка, представленная JavaScript выражением, оператором или последовательностью операторов. Выражение может содержать переменные и свойства существующих объектов.

Возвращаемое значение

Возвращает значение выполнения кода, переданного в функцию в виде строки. Если код не возвращает ничего — будет возвращено значение undefined .

Описание

eval() — функция глобального объекта.

Аргумент функции eval() — строка. eval() исполняет содержащееся в строке выражение, один или несколько операторов JavaScript. Не стоит вызывать eval() для определения значения арифметического выражения; JavaScript вычисляет их автоматически.

eval() можно использовать для вычисления значения арифметического выражения, записанного в строковом виде, на более поздней стадии исполнения. Предположим, существует переменная x . Можно отложить вычисление выражения, в котором содержится х , если присвоить переменной это выражение в виде строки (допустим, » 3 * x + 2 «), а затем вызвать eval() в более поздней точке кода.

Если аргумент, переданный eval() , не является строкой, eval() возвращает его неизменным. В следующем примере определён конструктор String , и eval() не вычисляет значение выражения, записанного в строковом виде, а возвращает объект типа String .

Это ограничение легко обойти при помощи toString() .

Если вы используете eval косвенно, вызовом его через ссылку, а не просто eval , в ECMAScript 5 это работает в глобальной области видимости, а не в локальной; это значит, что eval будет вызван в глобальной области видимости, а код будет выполнен с отсутствием доступа к локальным переменным в пределах области видимости, где он был вызван.

Не используйте eval без необходимости!

eval() — опасная функция, которая выполняет код, проходящий со всеми привилегиями вызывателя. Если вы запускаете eval() со строкой, на которую могут влиять злоумышленники, то вы можете запустить вредоносный код на устройство пользователя с правами вашей веб-страницы/расширения. Наиболее важно, код третьей стороны может видеть область видимости, в которой был вызван eval() , что может может привести к атакам, похожим на Function .

Также eval() , как правило, медленнее альтернатив, так как вызывает интерпретатор JS, тогда как многие другие конструкции оптимизированы современными JS движками.

Есть безопасные (и быстрые!) альтернативы eval() для общих случаев использования.

Доступ к свойствам

Вам не следует использовать eval() , чтобы конвертировать имена свойств в свойства. Рассматривая следующий пример, где свойство объекта используемое для доступа неизвестно до выполнения кода. Это можно сделать с eval:

Однако, eval() здесь не нужен. По факту, использование здесь его удивляет. Вместо него используйте доступ к свойствам, который быстрее и безопаснее:

Используйте функции вместо исполнения фрагментов кода

У JavaScript функции первого класса, что значит, что вы можете передавать функции как аргументы, хранить их в переменных или свойствах объектов и так далее. Многие DOM API созданы с учётом этого, так что вы можете (и вам следует) писать:

Замыкания также полезны как способ создания функций с параметрами без конкатенации строк.

Разбор JSON (конвертирование строк в JavaScript объекты)

Если строка, переданная в eval() , содержит данные (к примеру, массив: «[1, 2, 3]» ), а не код, вам следует рассмотреть JSON, позволяющий строке использовать подмножество JavaScript синтаксиса для представления данных. Смотрите также: Загрузка JSON и JavaScript в расширениях.

Заметьте, что синтаксис JSON ограничен в сравнении с JavaScript синтаксисом, многие валидные JavaScript литералы не распарсятся в JSON. К примеру, лишние запятые в конце выражений не разрешены в JSON, а имена свойств (ключи) в объектах должны быть в двойных кавычках. Будьте уверены использовать сериализацию JSON для создания строк, которые потом будут разбираться как JSON.

Передавайте данные вместо кода

К примеру, расширение, созданное изменять содержимое веб-страниц, должно иметь правила, определённые в XPath, а не JS коде.

Выполняйте код с ограниченными правами

Если выполнять код всё-таки необходимо, желательно это делать с уменьшенными привелегиями. Этот совет подходит, главным образом, к расширениям и XUL приложениям, которые могут использовать Components.utils.evalInSandbox.

Примеры

Использование eval

В следующем коде оба выражения содержат eval() , возвращающий 42. Первое определяется строкой » x + y + 1 «; второе — строкой » 42 «.

Использование eval для исполнения строки, содержащей операторы JavaScript

Следующий пример использует eval() для получения значения выражения str . Эта строка состоит из JavaScript выражений, печатающих в консоль, и, если x равен пяти, призывающих z значение 42, или 0 в противном случае. Когда второе выражение будет исполнено, eval() будет считать выражения выполненными, а также это установит значение выражению переменной z и вернёт его.

js eval function for executing a string representation of javaScript

In javaScript there is the eval function that can be used to execute a string representation of some javaScript code. It is generally something to be avoided for various reasons, and it it really must be used should be used with care. In projects where the string value is passed from user input there is the risk of introducing security problems if the input is not sanitized. In general if you can find a way to do what you want to do with eval by some other means do that instead.

There are other ways of evaluating javaScript code that involve other aspects of native javaScript such as the function constructor, as well as user space modules like jsdom. There is also ways or making parsers that will act as a way to make my own domain specific language rather than using eval to run javaScript code in string format. However that is a matter for a whole other post on something other than js eval.

The eval function should not be used if it can be avoided, the use of the eval function can slow things down, and can also open up some security concerns. I can not say that I use eval often, and even when I am in a situation in which I seems like I need to use it I do what I can to look for other options. Still this is a post on js eval, so then this will be a post on some of the ins and outs of the js eval function for what it is worth.

1 — Basics of js eval

In this section I will be starting out with just a few basic examples of eval in core javaScript as such these examples should work in just about all javaScript environments. Although I will be keeping these examples fairly simple I assume that you have at least some background with javaScript when it comes to getting started. There is more than one way of getting started of course beyond just the way that you might have started with javaScript. For example I have started by writing html files with embedded script tags and opening them up in a web browser using the file protocol. However it is also possible to get started in the javaScript console of a web browser, or use nodejs and just write sever side scripts outside of a web browser.

— Source is up on github

As with all my other posts on vanilla javaScript, the source code examples here can be found in my test vjs repository on Github. I do get around to editing and expanding my content on subjects such as eval and much more, and this repository would be where to make a pull request of you are on Github. There is also the comments section of this post that can be used as a way to bring something up, I have a lot of other things to do, but I will end up coming around to it sooner or later.

1.1 — js eval basic example

For a basic example of the js eval function I just stared out with a string of a very simple javaScript expression and passed that to the eval function. After doing so the result of that expression is returned to which I then just logged to the console.

Читать:
Какие особенности связи 1 к 1

So that is the basic idea of eval, it is just a ay to go about evaluating some javaScript code in a string format. There are other ways of doing just that such as with the Function constructor. However if I am ever in a situation in which i thing I might need to use eval or the function constructor I take a moment to try to find another way of doing so. It is generally agreed that the use of these options for running javaScript code can bring up both security and performance concerns that can often be avoided.

1.2 — js eval can create variables in the scope in which it is used

When the js eval function is used with a string of javaScript that contains the use of the var keyword to create a variable, and it is not used in strict mode, this can result in a variable being created in the scope in which eval is used.

This is one weird thing about the use of eval that a developer should be ware of when using it. Also again about using eval, if you can every thing of any way to go about not using it do that instead, and not just for this reason.

2 — Other ways to evaluate a little javaScript

There are a number of other ways to evaluate a little javaScript, often in the form of a string value that needs to be evaluated. In this section I will be going over what some of these options might be. Now all of these options will be available in all environments, for example in client side javaScript I might be able to use the Function constructor as a way to evaluate a javaScript string, but I can not use the e option of the nodejs binary in such an environment.

2.1 — The Function Constructor

One way other than eval would be to use the Function constructor where the body of javaScript code that would compose the function can be passed as a string to the Function constructor when it is called with the new keyword. This can then be used to evaluate a javaScript string by just appending what I want to evaluate with a return to make the result of the javaScript string the return value of the resulting function that will be returned by the constructor. I can then just simple call the function that is the result of doing this.

2.2 — The e option of the nodejs binray

When it comes to using node there is the e option of the node binary that can be used to run a little javaScript code that is given in the from of a string after the option when calling node from the command line.

3 — Conclusion

The use of eval is something that I can not say I use very often, or at all actually. There is generally always a way to go about not using it, and if so that is most likely the way that it should be done. Still it is nice to know that it is there when and if I am in a situation in which there is no other option. Using eval and the function constructor just does not strike me as a way that I should be writing and using javaScript, and there are additional concerns about using it that I have not covered in this post.

Eval: выполнение строки кода

Встроенная функция eval позволяет выполнять строку кода.

Строка кода может быть большой, содержать переводы строк, объявления функций, переменные и т.п.

Результатом eval будет результат выполнения последней инструкции.

Код в eval выполняется в текущем лексическом окружении, поэтому ему доступны внешние переменные:

Значения внешних переменных можно изменять:

В строгом режиме у eval имеется своё лексическое окружение. Поэтому функции и переменные, объявленные внутри eval , нельзя увидеть снаружи:

Без use strict у eval не будет отдельного лексического окружения, поэтому x и f будут видны из внешнего кода.

Использование «eval»

В современной разработке на JavaScript eval используется весьма редко. Есть даже известное выражение – «eval is evil» («eval – это зло»).

Причина такого отношения достаточно проста: давным-давно JavaScript был не очень развитым языком, и многие вещи можно было сделать только с помощью eval . Но та эпоха закончилась более десяти лет назад.

На данный момент нет никаких причин, чтобы продолжать использовать eval . Если кто-то всё ещё делает это, то очень вероятно, что они легко смогут заменить eval более современными конструкциями или JavaScript-модулями.

Пожалуйста, имейте в виду, что код в eval способен получать доступ к внешним переменным, и это может иметь побочные эффекты.

Минификаторы кода (инструменты, используемые для сжатия JS-кода перед тем, как отправить его конечным пользователям) заменяют локальные переменные на другие с более короткими именами для оптимизации. Обычно это безопасная манипуляция, но не тогда, когда в коде используется eval , так как код из eval может изменять значения локальных переменных. Поэтому минификаторы не трогают имена переменных, которые могут быть доступны из eval . Это ухудшает степень сжатия кода.

Использование внутри eval локальных переменных из внешнего кода считается плохим решением, так как это усложняет задачу по поддержке такого кода.

JavaScript eval() function

TL;DR JavaScript eval function is capable of executing JavaScript code passed as a string to it. The eval is a part of the JavaScript global object. The return value of eval() is the value of last expression evaluated, if it is empty then it will return undefined . Example:

The above code will result a “Hello World” in the console.

FYI eval() is also capable of executing multiple JavaScript statements.

The above code will result a “10” in the console.

But wait there is more to eval() than you think.

In the above examples eval() works in global scope having access to global scope. What happens if you call eval() inside a function ? Lets see.

This seems to be pretty normal. as eval() inside of function foo it has access to both global scope and local scope. Note that as variable z and y are created inside function foo their scope is limited to this function only.

Now comes the twist indirect call to eval(), consider the below example:

This is because this kind calling of eval is actually calling it from the global scope and it has no access to the current local scope i.e. foo that’s why we are getting a reference error for y .

Now comes use strict with eval(). Let us first check this example:

This is simple and normal, now lets run the same code in strict mode:

In the first example i.e. with out using the strict mode, eval executes a JS statement and adds the variables to the global scope. While in strict mode it will not do so. The variables will be limited inside of eval() only.

Lets check one more example:

What do you think this will do ? This will create a function test and add it to the global object ? No it will just evaluate the expression and thus it will return the function test that’s it. Also not that “(“ & “)” before & after function definition.

Unlike the previous example it will return undefined . So “(“ & “)” are important in case defining functions inside eval().

Beware!

Using eval() sometimes maybe extremely dangerous, it depends upon the programmer how he / she is using it. For example you are taking a mathematical expression as user input and you want to evaluate that, so you thought of using eval(). Instead of inputting a mathematical expression if the user inputs a malicious JavaScript code and eval() executes that code, the result might be extremely dangerous.

Похожие статьи