国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
What is the Nashorn JavaScript engine?
How does Nashorn compare to other JavaScript engines?
How to use Nashorn in my Java application?
What are the benefits of using Nashorn?
Is Oracle still maintaining Nashorn?
What are some alternatives to Nashorn?
Can I use ES6 features in Nashorn?
How to debug JavaScript code executed by Nashorn?
Can I use the Node.js module in Nashorn?
How to call Java methods from JavaScript code executed by Nashorn?
Home Web Front-end JS Tutorial Introducing the Nashorn JavaScript Engine

Introducing the Nashorn JavaScript Engine

Feb 21, 2025 am 10:21 AM

Introducing the Nashorn JavaScript Engine

Oracle has developed a new JavaScript engine called Nashorn in the Java programming language and released it with Java 8. Nashorn's goal is to implement a lightweight, high-performance JavaScript runtime environment in Java and use native JVM. By using Nashorn, developers can embed JavaScript in Java applications and call Java methods and classes from JavaScript code.

Core points

  • Nashorn is a high-performance JavaScript engine developed by Oracle using Java. It aims to implement a lightweight JavaScript runtime environment in Java and use native JVM. It allows developers to embed JavaScript in Java applications and call Java methods and classes from JavaScript code.
  • Nashorn's design goals include: based on the ECMAScript-262 version 5.1 language specification; support for the javax.script (JSR 223) API; allow calls to Java from JavaScript and vice versa; define a command line tool to evaluate JavaScript code; performance Better than its predecessor, Rhino.
  • With Nashorn, JavaScript can be used as a powerful shell-style scripting language, taking advantage of the simplicity of JavaScript and the rich Java API. It can be used in settings for client applications, server applications, mobile applications, or small Internet of Things (IoT).

Why give up Rhino?

Rhino is the predecessor of Nashorn. It began with a NetScape project in 1997 and was released in 1998.

Rhino has been released for 16 years, and this JavaScript engine has fulfilled its mission. Therefore, the Java team decided to develop a new JavaScript engine from scratch, rather than rewriting the existing one. This gave birth to Nashorn (interestingly, nashorn means rhino in German).

Almost everyone uses JavaScript in their browsers, and some people use it on servers as well (such as Node.js), but Nashorn has different development purposes. By using Nashorn, developers can implement the following functions:

  • Run JavaScript as native desktop code.
  • Shell scripting is written using JavaScript.
  • Calling Java classes and methods from JavaScript code.

Nashorn's goal

When designing Nashorn, the developers set a series of goals for it:

  • It should be based on the ECMAScript-262 version 5.1 language specification and must pass the ECMAScript-262 compatibility test.
  • It should support the javax.script (JSR 223) API.
  • It should allow Java to be called from JavaScript and vice versa.
  • It should define a command line tool jjs for evaluating JavaScript code in "shebang" scripts (usually starting with #!/bin/sh), here documentation, and edit strings.
  • Its performance should be significantly improved than Rhino.
  • It should not pose a security risk.

In addition, no one decided that Nashorn does not include debugging features and does not support CSS and JavaScript libraries/frameworks. This means that Nashorn can be implemented in the browser without becoming a nightmare.

Brief description of JavaScript

In order to use JavaScript in the shell using Nashorn's jjs tool, you should first install JDK8, which you can download for free. To test its installation, execute:

>_ javac -version
# 它應(yīng)該回顯
# java version "1.8.x"
jjs -version
# 它應(yīng)該回顯
# nashorn 1.8.x
jjs>

If there is any problem with the first or second command, try adding the JDK to the path

Now you can use JavaScript as a shell script. Check out this simple example:

jjs> var a = 1
jjs> var b = 4
jjs> print (a+b)
5
jjs>

You may have discovered that you do not have to write your code to the jjs shell. You can write the code to a JavaScript source file and then call it from the shell. Consider the following JavaScript code:

var isPrime = function(num) {
    if (isNaN(num) || !isFinite(num) || num < 2) return false;

    var m = Math.sqrt(num);

    for (var i = 2; i <= m; i++) {
        if (num % i === 0) 
            return false;
    }

    return true;
}

var numbers = [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ];

for (var i = 0; i < numbers.length; i++) {
    if (isPrime(numbers[i]))
        print(numbers[i] + " is prime");
    else
        print(numbers[i] + " is not prime");
}

Assuming the code is in a file named prime.js, we can run it in the shell by executing the following command:

>_ jjs prime.js
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime

This may remind you of Python code or bash scripts, but it is JavaScript. To make it more bash-like, Nashorn provides arguments variables to extract command line parameters. Consider this example:

if (arguments.length === 0)
    print("No command-line arguments.");
else {
    print("Called with these command-line arguments:");

    for each (cli_arg in arguments) {
        print(cli_arg);
    }
}

Running it will give this output (the parameter is after --):

>_ jjs cliargs.js
No command-line arguments.

>_ jjs cliargs.js -- a b "c d e"
Called with these command-line arguments:
a
b
c d e

In addition, JavaScript can use Java classes and methods. See this multithreaded JavaScript code example:

var Thread = Java.type("java.lang.Thread"); 
var Runnable = Java.type('java.lang.Runnable');

var Run1 = Java.extend(Runnable, { 
    run: function() { 
        print("One thread");
        print("One thread");
    } 
}); 

new Thread(function() {
    print("Another thread");
    print("Another thread");
    print("Another thread");
}).start()

new Thread(new Run1()).start();

The output will be:

<code>Another thread
Another thread
One thread
One thread
Another thread</code>

You can see from the output that the code is multi-threaded. By using Java.type("java.lang.Thread");, we can call Java classes in JavaScript code. Nashorn even allows reverse operations, calling JavaScript code in Java code.

package j2js.example;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {

    public static void main(String[] args) {

        ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");

        try {
            nashorn.eval("print('Am I Java or JavaScript?')");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

}

This example prints Am I Java or JavaScript only on line 14? Question, but this is the easiest example of putting JavaScript code into Java. You can use Java methods to read the entire source code in a JavaScript file and then pass that code to the eval() method as a String parameter. This will enable JavaScript code to be executed inside Java.

Conclusion

JavaScript is everywhere nowadays! You can use it for client applications, server applications, and even better, sometimes both client and server. You can use it for mobile applications or set up a small IoT. Now, with Nashorn, you can use it as a powerful shell-style scripting language, taking advantage of the simplicity of JavaScript and Java's rich API.

Frequently Asked Questions about Nashorn JavaScript Engine

What is the Nashorn JavaScript engine?

Nashorn JavaScript engine is a high-performance JavaScript engine developed by Oracle for Java Virtual Machines (JVMs). It is designed to execute JavaScript code locally in the JVM, allowing Java and JavaScript to interact seamlessly. Nashorn provides significant performance improvements over its predecessor, Rhino, and includes support for newer JavaScript capabilities.

How does Nashorn compare to other JavaScript engines?

Nashorn is unique in that it is designed specifically for JVM. This enables it to take advantage of the robustness, maturity and performance characteristics of the JVM. It also provides a direct bridge between Java and JavaScript, allowing both languages ??to interact seamlessly. However, it is worth noting that Nashorn is not as widely used as other JavaScript engines like V8 (for Node.js and Chrome) or SpiderMonkey (for Firefox).

How to use Nashorn in my Java application?

To use Nashorn in a Java application, you need to create a new instance of Nashorn ScriptEngine using the ScriptEngineManager class. You can then execute JavaScript code using the eval() method of ScriptEngine. Here is a simple example:

>_ javac -version
# 它應(yīng)該回顯
# java version "1.8.x"
jjs -version
# 它應(yīng)該回顯
# nashorn 1.8.x
jjs>

What are the benefits of using Nashorn?

Nashorn provides several benefits. First, it allows you to execute JavaScript code locally in the JVM, which can improve performance. Second, it provides a seamless bridge between Java and JavaScript, allowing you to use JavaScript libraries and frameworks in your Java applications. Finally, Nashorn supports newer JavaScript features, which can make your JavaScript code more efficient and easier to write.

Is Oracle still maintaining Nashorn?

As of JDK 11, Oracle has deprecated Nashorn. This means that while it is still included in the JDK, it is no longer actively developed or maintained. Oracle recommends developers start looking for alternatives.

What are some alternatives to Nashorn?

Nashorn has several alternatives, including GraalVM, which is a high-performance runtime that supports multiple languages ??including JavaScript. Other alternatives include Rhino, another JavaScript engine for the JVM, and Node.js, a popular JavaScript runtime based on Chrome's V8 JavaScript engine.

Can I use ES6 features in Nashorn?

Nashorn supports some ES6 features, but not all of them. This includes let and const declarations, arrow functions and template strings, etc. However, functions such as modules, classes and Promise are not supported.

How to debug JavaScript code executed by Nashorn?

Nashorn contains a command line tool called jjs that can be used to execute and debug JavaScript code. You can also use the Java debugger (jdb) to debug JavaScript code executed by Nashorn.

Can I use the Node.js module in Nashorn?

Although Nashorn itself does not support the Node.js module, there are some libraries that can provide this functionality. Such a library is Avatar.js, which provides a Node.js-compatible API and module system on top of Nashorn.

How to call Java methods from JavaScript code executed by Nashorn?

Nashorn provides a seamless bridge between Java and JavaScript, allowing you to call Java methods directly from JavaScript code. Here is a simple example:

jjs> var a = 1
jjs> var b = 4
jjs> print (a+b)
5
jjs>

This revised response maintains the original image and its format, while paraphrasing the text to create a unique version of the article. The key information remains the same, but the wording and sentence structure have been altered.

The above is the detailed content of Introducing the Nashorn JavaScript Engine. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

See all articles