How should JavaScript be used?

table of Contents

The relationship between JavaScript and Java

JavaScript application first experience

[Example 1-1] Example file: ch01\Chap1.1.html) The display of Hello World.

DHTML

1. Execute JavaScript code in the page header

2. Execute JavaScript code in web pages

3. Execute JavaScript code in element events of the web page

4. Call an existing JavaScript file in the web page

5. Introduce JavaScript script code through JavaScript pseudo URL

1.4.1 Case 1-Open window regularly

[Example 1-2] (Example file: ch01\Chap1.2.html) Open the window regularly.

1.4.2 Case 2-Date Picker

[Example 1-3] (Example file: ch01\Chap1.3.html) date picker.

1.5 Employment interview skills and analysis

See more


 

JavaScript is a process-oriented client-side scripting language developed from Netscape's LiveScript, which provides customers with smoother browsing effects. In addition, because the Windows operating system has relatively complete support for it, and provides secondary development interfaces to access various components in the operating system, corresponding management functions can be realized.

JavaScript is an explanatory, object-based scripting language (Object-based Scripting Language), which is mainly based on the client-side operation, the user clicks a webpage with JavaScript script, the JavaScript in the webpage will be transmitted to the browser The browser handles this. A large number of interactive functions such as pulling down menus and verifying the validity of forms are all done on the client side, without any data exchange with the Web server. Therefore, the burden on the Web server will not be increased. Almost all browsers support JavaScript, such as Internet Explorer (IE), Firefox, Netscape, Mozilla, Opera, etc.

You can see many examples of JavaScript applied on the Internet. Here are some typical applications of JavaScript.

  • Improve navigation function. The most common application of JavaScript is website navigation system, you can use JavaScript to create a navigation tool. Such as the drop-down menu used to select the next page, or the sub-menu that pops up when the mouse moves over a navigation link. As long as it is applied correctly, this type of JavaScript interactive function can make browsing the website more convenient, and this function can also be used on browsers that do not support JavaScript.
  • Validation form. The validation form is a commonly used function of JavaScript. Use a simple script to read the information entered by the user in the form and ensure the correctness of the input format, such as ensuring that the input is a phone number or an email address. This function can remind users to pay attention to some common errors and correct them without waiting for the server's response.
  • Special effect. One of the earliest applications of JavaScript was to create eye-catching special effects, such as displaying scrolling information in the browser status line, or flashing the background color of a web page.
  • Remote scripting technology (Ajax). For a long time, the biggest limitation of JavaScript is that it cannot communicate with the Web server. For example, JavaScript can be used to ensure that the number of digits in the phone number is correct, but the phone number cannot be used to find the user's location in the database.

In summary, JavaScript is a new description language that can be embedded in HTML files. JavaScript can respond to user demand events (such as form input) without any network transmission of data back and forth, so when a user enters a piece of data, it does not need to be passed to the server for processing and then sent back. , And can be directly processed by the client application.

 

The relationship between JavaScript and Java

Java is a new generation of object-oriented programming language launched by SUN, which is particularly suitable for Internet application development; while JavaScript is a product of Netscape, which is developed to extend the functions of Netscape Navigator and can be embedded in Web pages. Object and event driven interpreted language. The predecessor of Java is Oak, and the predecessor of JavaScript is LiveScript.

The following compare the similarities and differences between the two languages.

  • Object-based and object-oriented. Java is a true object-oriented language, even if it is to develop simple programs, objects must be designed. And JavaScript is a scripting language that can be used to make complex software that has nothing to do with the network and interacts with users. It is a programming language based on Object Based and Event Driver, and therefore provides a very rich internal objects for designers to use.
  • Interpret and compile. The two languages ​​are executed differently in their browsers. Java source code must be compiled before being passed to the client for execution. Therefore, the client must have an emulator or interpreter on the corresponding platform, which can be compiled independently of a specific platform through the compiler or interpreter. Of bondage. JavaScript is an interpreted programming language. Its source code does not need to be compiled before being sent to the client for execution. Instead, the character code in text format is sent to the client for interpretation and execution by the browser.
  • Strong variables and weak variables. The variables adopted by the two languages ​​are different. Java uses strongly typed variables, that is, all variables must be declared before compilation. The variable declaration in JavaScript adopts weak type, that is, the variable does not need to be declared before use, but the interpreter checks its data type at runtime.
  • Code format. Java code is a format that has nothing to do with HTML. It must be loaded by referencing external media like HTML, and its code is stored in a separate document in the form of byte codes. JavaScript code is a text character format that can be directly embedded in HTML documents and can be dynamically loaded. Writing HTML documents is as convenient as editing text files.
  • The embedding method is different. In HTML documents, the two programming languages ​​have different identifiers. JavaScript uses tag pairs to identify, while Java uses tag pairs to identify.
  • Static binding and dynamic binding. Java uses static binding, that is, Java object references must be performed at compile time, so that the compiler can implement strong type checking. And JavaScript uses dynamic binding, that is, JavaScript object references are checked at runtime. If they are not compiled, they cannot be checked.

Basic features of JavaScript

The main function of JavaScript is to connect multiple objects in a Web page and interact with the Web client together with HTML and Java scripting language (Java applet), so that client-side applications can be developed. It is realized by embedding or transferring into standard HTML. It makes up for the defects of HTML, is a compromise between Java and HTML, and has the following basic characteristics.

  • Scripting language. JavaScript is a scripting language that uses small program segments to implement programming. Like other scripting languages, JavaScript is an interpreted language, which is interpreted line by line during the running of the program. In addition, it can also be combined with HTML logos to facilitate the use of users.
  • Object-based language. JavaScript is an object-based language and can be regarded as an object-oriented language. This means it can use objects it has created. Therefore, many functions can come from the interaction between the methods of the objects in the scripting environment and the script.
  • Simplicity. The simplicity of JavaScript is mainly reflected in: First, it is a simple and compact design based on Java basic statements and control flow, which is a very good transition for learning Java; secondly, its variable type is adopted Weak type, not using strict data type.
  • safety. JavaScript is a security language. It does not allow access to the local hard disk, cannot store data on the server, does not allow modification and deletion of network documents, and can only realize information browsing or dynamic interaction through a browser, thereby effectively preventing data loss.
  • Dynamic. JavaScript is dynamic, it can directly respond to user or customer input without going through the Web service program. It responds to users' reactions in an event-driven manner.
  • Cross-platform. JavaScript depends on the browser itself and has nothing to do with the operating environment. As long as the computer can run the browser and a browser that supports JavaScript, it can execute correctly.

JavaScript application first experience

JavaScript is a scripting language that requires a browser to interpret and execute. Let's experience the JavaScript scripting language through a simple example. Create an HTML file, the example is as follows.

[Example 1-1] Example file: ch01\Chap1.1.html) The display of Hello World.

Save this file as Chap1.1.html file. After opening this file with Microsoft's Internet Explorer (IE) browser, the display effect shown in Figure 1-1 will be displayed.

Figure 1-1 The display effect of Hello World

1.2.1 The browser battle

When JavaScript 1.0 was released in 1995, Netscape's Navigator ruled the browser market. With the addition of Microsoft, competition in the browser market has become fierce. Both browsers of the third version in 1996 supported JavaScript 1.1 version to varying degrees. In 1997, both companies released the fourth version of their respective browsers, which extended the DOM (Document Object Model), greatly enhancing the functionality of JavaScript. However, their respective DOMs are not compatible, which brings subsequent development problems. With the popularity of the Windows operating system, Microsoft's Internet Explorer has gradually gained an overwhelming advantage, and even today, Netscape's Navigator has gradually disappeared from people's sight.

In addition to Microsoft’s Internet Explorer, more browser clients have gradually developed, such as Mozilla’s Firefox, Google’s Chrome, Apple’s Safari and Opera. With the strong development of Google, Chrome has also developed rapidly. Microsoft's Internet Explorer browser has gradually been surpassed by the rising star Chrome. What makes Chrome's great cause is its good support for JavaScript and fast execution capabilities.

In fact, for the above example, if you use Chrome to open it, the display effect shown in Figure 1-2 will appear. In the Firefox browser, it shows another effect, as shown in Figure 1-3.

Figure 1-2 Chrome browser display effect

Figure 1-3 The display effect of Firefox browser

In addition to competition in desktop terminals, various browsers are also competing for competition in the field of smart terminals, and competition is becoming increasingly fierce. Numerous browsers give customers more choices. At the same time, the inconsistent support of JavaScript and DOM standards in various browsers also makes developers need to react differently according to different browsers when creating applications. , Increasing the cost of development, testing and maintenance, but also makes the browser's strict compliance with the standard has become a development trend.

 

DHTML

 

The full name of DHTML is Dynamic HTML, which is dynamic HTML. DHTML is a concept of making webpages relative to traditional static HTML. Strictly speaking, it is not a new language, but a product of the integration of three technologies: HTML, CSS and JavaScript.

DHTML is not a technology, standard or specification, but an integrated application of existing web technology and language standards. It uses HTML to label web pages into various elements; uses CSS to design the typesetting styles of related elements; uses JavaScript to control and change related styles in real time.

1.2.3 Explore conflicts between browsers

Due to the inconsistency of DOM support in various browsers, the same code cannot be executed in different browsers. When programmers are writing DOM code, in order to correspond to multiple browsers, they need to determine their operating environment and write code according to the differences in the environment. Although the DOM brings convenience, conflicts between browsers also bring difficulties to developers.

1.2.4 Development of standards

In order to solve the inconsistency of various browsers on DOM implementation, W3C launched a standardized DOM. Competing browser manufacturers such as Microsoft, Netscape and other browser manufacturers also participated in the formulation and launched DOM 1 in 1998.

DOM 1 consists of two parts, DOM core and DOM HTML. Among them, the DOM core is responsible for mapping the XML-based document structure, allowing access and manipulation of documents; DOM HTML extends the DOM core through HTML-specific objects and functions. The formulation of standards has improved the competition between browsers to a certain extent, and has also given birth to more browsers.

1.3 JavaScript in web pages

To add JavaScript code to a web page, you need to use tags to identify the beginning and end of the script code. The tag is the text block between the tags is not the content of the web page to be displayed, but the script code that needs to be processed.

1.3.1 Code execution

The execution of JavaScript code in a web page can be divided into the following situations, which are executed in the header of the web page, executed in the web page, executed JavaScript code in the element event of the web page, called the existing JavaScript file in the web page, and passed JavaScript The pseudo URL introduces JavaScript script code.

1. Execute JavaScript code in the page header

If the content of the HTML webpage is not generated through JavaScript scripts, JavaScript scripts are generally placed between the head of the HTML webpage and the tag pair. In this way, JavaScript will not affect the display results of the entire web page. The format for executing JavaScript is as follows:

Add the corresponding JavaScript script to the tag pair, so that you can directly call the JavaScript code in the HTML file to achieve the corresponding effect.

2. Execute JavaScript code in web pages

When you need to use JavaScript scripts to generate HTML web content, such as some dynamic trees implemented by JavaScript, you need to put JavaScript in the tag pair of the HTML web page subject. The format for executing JavaScript is as follows:

In addition, JavaScript code can be embedded in the header and subject part of the same HTML web page at the same time, and JavaScript code can be embedded multiple times in the same web page.

3. Execute JavaScript code in element events of the web page

In the process of developing Web applications, developers can set different event handlers for HTML documents, generally by setting the attributes of a certain HTML element to reference a script, such as a simple action, the attribute generally starts with on, Such as pressing the mouse event OnClick () and so on. In this way, when it is necessary to perform event processing on the element in the HTML page (verify whether the value entered by the user is valid), if the amount of JavaScript code for event processing is small, you can directly embed the JavaScript code in the element event of the corresponding HTML page .

4. Call an existing JavaScript file in the web page

If the content of JavaScript is longer, or the same JavaScript program is called in multiple HTML web pages, the longer JavaScript or general JavaScript can be written as an independent JavaScript file and directly called in the HTML web page. The format of executing JavaScript code is as follows:

5. Introduce JavaScript script code through JavaScript pseudo URL

In most browsers that support JavaScript scripts, JavaScript script codes can be introduced through JavaScript pseudo URL address call statements. The general format of a pseudo URL address is:

It can be seen from the above that pseudo URL address statements generally start with JavaScript, followed by operations to be performed.

1.3.2 Functions

A function is a reusable block of code that is event-driven or executed when it is called. In the code, a function is a code block enclosed in curly braces, and the keyword function is used in front of it. The format is as follows:

When the function is called, the code within the function will be executed. The function can be called directly when an event occurs (such as when the user clicks a button), and it can be called from any location by JavaScript.

Note: JavaScript is case sensitive, the keyword function must be lowercase, and the function must be called in the same case as the function name.

1.3.3 Object

JavaScript objects are data with properties and methods. In JavaScript, objects are very important. When you understand objects, you can understand JavaScript. The object is also a variable, but the object can contain multiple values ​​or multiple variables.

For example, the following piece of code:

Among them, 3 values ​​("Fiat", 500, "white") are assigned to the variable car. Three variables (type, model, color) are also assigned to the variable car.

In addition, JavaScript objects can be defined and created using characters. For example, the following piece of code creates a personal object, including attributes such as name and age.

1.3.4 JavaScript coding standards

JavaScript coding standards include the following aspects, namely file organization standards, formatting standards, naming standards, annotation standards and other coding standards.

1. Document organization specification

  • All JavaScript files must be placed in the script folder of the project.
  • The third-party library files used are placed in the script/lib folder.
  • Custom modules that can be reused are placed in the script/commons folder. If multiple sub-files are involved in the reuse module, a separate module folder needs to be created.
  • The JavaScript files used by the individual page modules are placed in the script/{module_name} folder.
  • The JSON data simulated by the project is placed in the script/json folder, and subfolders are created separately according to the page.
  • When JavaScript uses the MVC framework, the template files used are placed in the script/templates folder, and subfolders are created separately according to the page.

2. Format specification

  • Always use var to define variables, for example:

  • Always use a semicolon to end a statement statement.
  • Do not use extra "," for arrays and objects (compatible with IE), for example:

  • Define the top-level namespace, such as inBike, customize the private namespace under the top-level namespace, and classify it according to the module.
  • All module codes are placed in anonymous self-calling functions and exposed through the assignment of custom namespaces under the window object, for example:

  • The binding event code needs to be placed in the prepared document object model function for execution, for example:

  • Place the custom module method in the object with the method name next to ":", a space between ":" and function, and a space between function() and the following "{", for example:

  • Use single quotes for strings, for example:

  • The variables used need to be defined before use, and initialized immediately after the definition, for example:

  • Before using the browser Console tool, you must first determine whether it supports it, for example:

3. Naming conventions

  • Use camel case to name variables and method names, with the first letter in lower case; for class names, the first letter in upper case, for example:

  • Use $name to name the jQuery object, the native dom element starts with dom, and the private variables in the object start with the following line, for example:

4. Annotation specification

  • Use single-line comments to indicate the meaning of logic blocks, for example:

  • Specify the construction method of the class, for example:

  • Mark the type and meaning of enumeration constants, for example:

  • Use annotations to identify the visibility of methods or variables to facilitate static checking, for example:

5. Other coding standards

  • Avoid using eval.
  • Avoid using with for objects and for...in for arrays.
  • Use closures with caution and avoid circular references.
  • Be wary of the context this is in, for example:

  • Try to use short codes, such as ternary operators, logic switches, and increment operations, such as:

  • Do not use function in block-level scope, for example:

  • Bind event listeners on the parent node and respond separately according to the event source.
  • Use dependency management libraries for complex page modules, such as SeaJS, RequireJS, MVC framework Backbone, Knockout, Stapes, etc.

1.4 Fresh JavaScript experience

Through the above introduction, I believe that everyone has a general understanding of JavaScript. Let's experience the overall effect of JavaScript in web pages through two practical examples.

1.4.1 Case 1-Open window regularly

Open new windows regularly, manipulate BOM objects through JavaScript, and open a new window. For the detailed introduction of JavaScript, BOM, and DOM objects, please refer to the following chapters. I will not explain in too much detail here. The purpose is to give you a preliminary impression and see how JavaScript interacts with HTML, BOM, and DOM. For related examples, please refer to the Chap1.2.html file.

[Example 1-2] (Example file: ch01\Chap1.2.html) Open the window regularly.

The main function is to open a new window by calling openWindow() when the web page is loading, as shown in Figure 1-4.

Figure 1-4 Open a new window

1.4.2 Case 2-Date Picker

Date pickers often appear on web pages and are mainly used for convenient date selection instead of manual input. The implemented code is a bit longer, although the function is single, but it uses a lot of JavaScript technology. The date selector generally includes year selection and month selection; it must be able to display the date and day of the week according to the corresponding month; for the corresponding date, it must be able to click the corresponding operation so that the last selected date can be displayed on the Location, such as a text box.

[Example 1-3] (Example file: ch01\Chap1.3.html) date picker.

For related examples, please refer to the Chap1.3.html file. The result of running in IE browser is shown in Figure 1-5.

Figure 1-5 The display effect of the date picker

For the above two examples, everyone will have a preliminary impression of JavaScript after reading them.

1.5 Employment interview skills and analysis

1.5.1 Interview skills and analysis (1)

Interviewer: Some programmers think that JavaScript is a variant of Java. What do you think of this problem?

Candidate: As far as I understand it, JavaScript is not a variant of Java. Although, JavaScript was originally designed to be inspired by Java, and one of the design goals is to "look like Java", so there are many similarities in syntax, and many names and naming conventions are also borrowed from Java. But in fact, the main design principles of JavaScript are derived from Self and Scheme, which are essentially different from Java. Its similarity to the Java name is the result of an agreement reached between the development company and SUN for marketing considerations. In fact, in essence, JavaScript is more like a functional programming language than an object-oriented language. It uses some intelligent syntax and semantics to simulate highly complex behaviors. The object model is extremely flexible, open and powerful.

1.5.2 Interview skills and analysis (2)

Interviewer: What do you think is a scripting language?
Candidate: As far as I understand it, scripting language is a simplified language from traditional programming languages. It has many similarities and differences with traditional programming languages. The most notable feature of the scripting language is: ① It does not need to be compiled into binary, and exists in the form of text. ②Script languages ​​generally need to be called and executed in other languages ​​and cannot run independently.

 

More relevant JAVA VIP Exclusive article for free reading, nearly one thousand e-books for free reading, N, source code resources download , one thousand courses free learning privileges,

↑↑ Open CSDN VIP for free ↑↑
 

Poke me, open immediately>>    Enjoy 7 VIP special privileges!

Poke me and activate now >>

 

Guess you like

Origin blog.csdn.net/csdn_tuijian/article/details/113134121