First, the object
In general: Everything is an object, and the Object = Property + method, the property is the object's variable (property value), the method is the object's function. In JS, the object is the data (variable), and the properties and methods are the members of the object.
For example, create a string variable that has the properties and methods of the string object
1. Using existing objects
var txt = "Hello"; txt.length=5txt.indexof ()
A string object is created, you can use the properties and methods of the string, or you can add new properties and methods to the existing object
2. Create a new object
person=New Object ();p erson.firstname= "Bill";p erson.lastname= "Gates";p erson.age =56;p erson.eyecolor= "Blue";
A new object was created and four properties were added
3. Accessing Properties and methods
Access properties: object. Property Txt.length Call Method: object. Method
Txt.replace ()
PS: In object-oriented, the hump command is more appropriate than the underscore command
Second, function
Two features: 1, reusable code block
2, event-driven, invoke execution. It means you use it when you want it, don't use it when you don't want it.
1. No parameter function
Grammar:
function functionname () {This is the code to execute}
Create:
function myFunction () {alert ("Hello world!" );}
2, with parametric function
Grammar:
function myFunction (VAR1,VAR2) {This is the code to execute}
Create:
function myFunction (name,job) {alert ("Welcome" + name + ", the" + Job);}
PS: When called, the parameters correspond in order.
3. function with return value
Syntax: Plus return statement
Create:
function myFunction () {var x=5; return x;}
PS: Stop execution when a function executes to a return statement or executes to the last statement
The return value of this function is 5 and can be assigned to a variable
var value = MyFunction ()
Value is 5.
The return value is optional, and it has another use: just to exit the function
function MyFunction (b) {if (a>b) { return; } x=a+B} If a>b, the function does not execute X=A+B
4. Local and global variables
Life cycle: Local variables are deleted after the function has run out
Global variables are deleted when the page is closed
Create a global variable within the function:
Carname= "Volvo";
Carname is not declared with Var, it is assigned a value, and this carname variable is now a global variable. Executed inside the function, too.
PS: Even if the variable is declared as a global variable, it must be executed once for the function to take effect.
JS Basic ③