JavaScript "Basic article"

Source: Internet
Author: User
Tags script tag

One. Script tag

JavaScript is often used in the context of other languages, such as when we use JavaScript in markup languages such as html,xhtml, we need to encapsulate the JavaScript code in the script tag whenever the browser reads the script. will not process its content in a html,xhtml way, but will allow the JavaScript engine built into the browser to execute the contents of the SCRIPT element

Type property: There are a lot of web scripting languages, not just JavaScript, so we use the type attribute to define the script type, and the JavaScript type value is Text/javascript

CharSet properties: Defines a set of character encodings for a script, typically without setting unless the script requires an encoding set that is completely different from the document

Defer property: If set to "defer", indicates that the script does not generate any document content, so the browser can process the rest of the page in advance and process the script section when the page processing is finished and the display is ready. The defer property can increase the loading speed of pages, especially those that reference a large number of JavaScript code or a large JavaScript library.

SRC attribute: Represents the external JavaScript file that is required to be loaded

Two. JavaScript data types and variables

Feature: Weak data type

The data type of a variable is the type resolution of the data stored in a variable by the JavaScript scripting engine, and unlike other languages, the same variable can hold different types, which is the dynamic type of JavaScript, which means that variables hold different data types in different contexts. But the dynamic type also has drawbacks, if you want two numbers to perform the addition, but the JavaScript engine interprets the variable that holds one of the numbers as the string data type, the result is to concatenate the two strings instead of the sum of the two numbers.

Three basic data types:

There are three types of strings, numbers, and Boolean types. When using these three basic types, the JS engine is automatically encapsulated into three objects: String,number,boolean. Allows you to use the properties and methods in the object for variables of the base type. When a method or property call is complete, the temporary object is discarded.

String type

1. String encoding

When using special symbols in strings, the escape character \ is very useful, but this useful is based on the character has the corresponding ASCII code, when processing some non-ASCII characters, ' \ ' is useless, these situations are usually encountered in Ajax, At this point we are going to use global functions encodeURI and encodeURIComponent. Using this method to encode non-ASCII code characters, it is converted from ASCII or non-ASCII code to uriencoding characters, and of course there are corresponding decoding methods decodeURI and decodeURIComponent

Boolean type
Input Results
Undefined False
Null False
Boolean value Boolean value
Digital If the number is 0 or nan, the result is false
String Empty string is False
Object True
Number Type

1. Scope

Although JavaScript can support larger numbers, some functions can only support numbers between -2e31 and 2e31 (about 2.1 billion).

2. Special two numbers, Infinity (positive infinity) and-infinity (negative infinity)

3. Global function parseint () and parsefloat ()

Whether the string is an integer or a floating-point number, one returns the integer part and one returns the floating-point number part. It is noteworthy that the second parameter of parseint () is the binary

4. Special case of global function number conversion

Input Results
Undefined NaN (not a number) type
Null 0 (Nan is returned in IE)
Boolean value True=1;false=0 (return nan in IE)
Digital numeric value
String Integer or floating-point number, depending on the string
Object NaN

Two special variables: null

1. A variable that has already been defined, and is assigned a value of NULL. The assignment is null, indicating that no memory space has been requested for the variable, so it cannot be called

Undefined

1. Variables that are not defined

2. variable is defined, but no value is assigned

Determine if the variable is initialized:

if (Var) {}//If the variable is null or undefined will return false.

         

Three. Function

  

Functions do not need to say much, it is worth noting that in JavaScript, the definition of the class (JS should be called the prototype object) is the same way as the definition of the function, except that different usages lead to the choice of calling a function or creating an object

Three ways to create a function: declarative/static

When the page loads, it parses the declarative function and uses its parsing results each time the function is called

function functionname (param1) {//differs from Java, does not require variable type  return ...;      }
Dynamic/Anonymous

The function is also an object, because all objects in JS, we can create a function like object creation, when the JavaScript processing application, unlike the declarative function, each time the anonymous function is called, the function will be created.

    var helloword=new Function ("name", "Window.alert (' Hello: ' +name);");
Literal type of
    var helloworld=function () {        window.alert ("Hello World");    }

Some differences from Java functions:

1.arguments variables can accept indeterminate arguments, and when you pass in multiple arguments, even if no formal parameters are accepted, we can manipulate the arguments passed in using the arguments variable inside the function. And JavaScript does not have a function overload, JavaScript always invokes the last defined overloaded function.

2.JavaScript can be nested functions, internal functions have access to external functions, external functions do not have access to internal functions, the keynote function does not have access to internal functions, there is a complex situation

function Outerfunction (Base) {  var punc= "!" ;   return function (EXT) {     return base+ext+punc;   }  }

What is the working mechanism of nested functions? Is there a violation of the scope rule? What state is in when the function terminates? Can the memory occupied by local variables be reclaimed by the garbage collection mechanism?

The answer is uncertain, whenever a new scope is created in a JavaScript application, if necessary, creates a related scope bubbling, which encapsulates the scope, the function is executed in the wrapper, and when executed, the scope is generally released. But when an intrinsic function is the return value of an external function and assigns a value to a variable, the scope of the inner function is appended to the external function, and the outer function scope is appended to the key application city, with the additional purpose of guaranteeing the integrity of the internal and external function parameters and variables. The function literal created by the intrinsic function is then assigned to the variable in the keynote program.

Four. Javascrip Event Driver

2.1 Event Overview

2.2 Event Categories

Mouse events: mouse events with mouse actions, such as Click,mousedown,mouse

Keyboard event: Input trigger keyboard event

HTML events: HTML events are also triggered when the browser loads HTML

Other events: Ajax requests

2.3 Event-Driven first program
<Scripttype= "Text/javascript">    functionHelloWorld () {Window.alert ("Hello World"); }</Script><S:formAction= "Add"namespace= "/regist">    <S:submitvalue= "Submit"onclick= "HelloWorld ();"/></S:form>
2.3 Actual usage-Access CSS Properties
//Access internal CSS Properties<Scripttype= "Text/javascript">    functionChangeColor (event) {varColor=Event.value;        Window.alert (color); if("White"==color) {            varDiv1=document.getElementById ("Div1"); Div1.style.background=" White"        }Else{            varDiv1=document.getElementById ("Div1"); Div1.style.background="Black"; }    }</Script><Divstyle= "Width:300px;height:300px;background-color:red"ID= "Div1">    <!--This represents the current element itself -    <inputtype= "button"onclick= "ChangeColor (this)"value= "BLACK"/>    <inputtype= "button"onclick= "ChangeColor (this)"value= "White"/></Div>//Access external CSS Properties<Scripttype= "Text/javascript">    //gets the class selector in css/mycss.css all    varCssrules=document.stylesheets[0].rules; functionChangeColor (event) {varColor=Event.value;        Window.alert (color); if("White"==color) {            //Cssrules[0] represents the first style in Mycss.csscssrules[0].style.background="Green"; }Else{cssrules[0].style.background="Black"; }    }</Script>

Five. DOM (Document Object model) programming

  

3.1 What is DOM programming? The X 3.2 DOM specification considers HTML pages as Dom trees 

  

      

Six. Forms, form events, and validation

  

Seven. To create a custom object

Two ways to create objects:

1. Create an object instance, and then add properties and methods

2. Use literal constants

      var dog={name:"small White"};

Window.alert (Dog.name);

Three strategies for creating objects

1. Factory mode

2. Constructor mode

3. Dynamic Prototyping Mode

Eight. Three main features of object-oriented

In JavaScript everything is object, and all objects inherit the function of object objects, we used the built-in objects in the JS engine and the objects in the browser Document Object model, so how to create a custom object? Children who have studied Java should know that in Java we create an instance by defining the class and using the new class. In JavaScript, we refer to the concept of class as a prototype, the object class is responsible for providing constructors to create objects that can allocate memory for an object and contain all of its properties. The object also provides a prototype property that allows us to extend the built-in objects, as well as extend the properties and methods of our custom objects, a bit like static in Java, where properties and methods belong to the prototype (class) itself.

  

Object class

The object class is the base class for all JavaScript classes and is responsible for providing the framework for innovative objects, other objects in JavaScript, and allocating memory through the constructor of object

Main properties of the object class

Constructor: Constructors for objects

Prototype (static): Gets the prototype object of the class.

Main methods of the object class

hasOwnProperty: Whether it belongs to a property defined by this class

Isprorotypeof (object): Whether the prototype of the specified class

ToString (): Returns the string corresponding to the object

ValueOf (): Returns the original type value corresponding to the object

  

Packaging

Encapsulation is the encapsulation of an abstract attribute and the operation of a property, the property is protected internally, and the other part of the program can be manipulated only by an authorized operation (function).

function Person (name,age) {  var name=name;   equivalent to the private  var age=age in Java;   equivalent to private this in Java  . getname=function() {         return  name;     This . SetName (myName) {       name=myName;  }  }

Note: Methods defined with prototype cannot access the private variables and private methods of the prototype '

Inherited

Unlike single inheritance in Java, JavaScript can implement multiple inheritance, and the way that JavaScript implements inheritance is "object Impersonation"

functionpeople (name,age) {varName=name; varAge=Age ;  This. getinfo=function(){    returnName+ "and" +Age ;} }functionStudent (name,age) { This. people=people;  This. people (Name,age);//Object Impersonation}varStudent=NewStudent ("Dyp", 20); Student.getinfo ();

Polymorphic

The so-called polymorphic, refers to a reference in different situations in a variety of states, in the Java polymorphic refers to a reference to the parent class, to invoke the method implemented in different word classes. JS is actually stateless, is a dynamic language, the type of a variable is in the process of running by the JS engine to determine,

 

JavaScript "Basic article"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.