Knowledge sharing: basic JavaScript syntax

Love to program 2021-01-22 16:55:05
knowledge sharing basic javascript syntax


JavaScript

brief introduction

JavaScript Is an object-oriented capability 、 Interpretive programming language . A little bit more specific , It is based on object and event driven and relatively secure client-side scripting language . Its main purpose is , Verify the data sent to the server 、 increase Web Interaction 、 Enhance user experience .

JavaScript The composition of

ECMAScript It's just the basis of the language , And Web The browser has no dependencies , On the other hand, a more perfect script language can be built on the basis of basic syntax .JavaScript It needs a certain environment to run , Out of the environment JavaScript Code can't run ,JavaScript It can only work in a specific environment .JavaScript The running environment is generally composed of the host environment and the runtime environment , Where the host environment is generated by the shell , Such as Web A browser is a shell program , It provides A host environment that can control browser windows . The runtime environment consists of... Embedded in the shell JavaScript engine ( Also known as JavaScript Interpreter ) Generate , In this environment JavaScript Ability to generate built-in static objects , Initialize the execution environment, etc .

Web Browser custom DOM Components , A document model described in an object-oriented way .DOM It defines representation and modification file What you need 、 The behavior and properties of these objects and the relationship between them .DOM object , We use the traditional method (javascript) The object of acquisition .DOM Belong to browser , instead of JavaScript The core content of the provisions in the language specification .

Ahead DOM To operate documents in browser , And in order to control the behavior and operation of the browser , The browser also provides BOM( Browser object model ).

ECMAScript( Basic grammar )

JavaScript The core grammar of ECMAScript Describes the syntax and basic objects of the language

DOM( Document object model )

Document object model (DOM)—— Describes the methods and interfaces for handling web content

BOM( Browser object model )

Browser object model (BOM)—— Describes the methods and interfaces for interacting with browsers

development tool

  1. browser :Chrome
  2. development tool :Hbuilder X
  3. Go to the browser console Console:F12

    The function of the console :

    console Object represents the JavaScript Console , Used to run JavaScript command , It's often used to display error messages on Web pages .Elements Used to debug web pages html and css Code .

Basic usage

JS Need and HTML It works when used together , We can directly or indirectly put JS The code is embedded in HTML On the page .

inline JS : Inside the label js Code

Inside JS : It's defined in script Inside the label js Code

external JS : A separate js file , stay HTML Pass through script Tags introduced

We can JavaScript Code placed in html Anywhere in the file , But we usually put it on the web head perhaps body part . Because the page is loaded from top to bottom , And this is the js Code running has an impact .

Put it in <head> part , The most common way is in the page head Partial placement <script> Elements , Browser parsing head Part of it will execute the code , Then I'll parse the rest of the page .

Put it in <body> part ,JavaScript The code will execute when the web page reads the statement .

inline JS:

<button onclick="alert('you clicked hered!!!')">click here</button>

Inside JS:

<script type="text/javascript" charset="utf-8">
alert('this is inner js code')
</script>

external JS file :

hello.js

alert('this is a outter js document');

hello.html

<!-- In need of use js Of html Page in -->
<script src="js/hello.js" type="text/javascript" charset="utf-8"></script>

JavaScript Basic grammar

Statements and comments

JavaScript The execution unit of the program is line (line), That is, line by line . In general , Each line is a statement .

sentence (statement) It's an operation to accomplish a certain task , The statement ends with a semicolon , A semicolon means the end of a statement . Multiple statements can be written on one line ( It's not recommended to write code like this ), But when you write more than one statement on a line , The statement must end with a semicolon .

Expressions don't need to end with a semicolon . Once you add a semicolon after the expression , be JavaScript The engine treats expressions as statements , This will produce some meaningless sentences .

Single-line comments : use // At first ;
Multiline comment : Put it in / and / Between .
compatible html Annotation mode :<!-- -->

Identifiers and keywords

identifier It's just a name , Used to name variables and functions , There are specific rules and norms

The rules :

from Unicode Letter 、_、$、 Digital composition 、 Chinese composition
(1) Cannot start with a number
(2) Can't be keywords and reserved words
(3) Case sensitive

standard :

(1) See the name and know the meaning
(2) Hump naming or underlining rules

keyword Also called reserved word , Be being JavaScript A word with a special meaning

arguments、break、case、catch、class、const、continue、debugger、default、delete、do、else、enum、eval、export、extends、false、finally、for、function、if、implements、import、in、instanceof、interface、let、new、null、package、private、protected、public、return、static、super、switch、this、throw、true、try、typeof、var、void、while、with、yield、Infinity、NaN、undefined

Variable

A variable is a named memory space for storing data , Data can be stored in variables , You can also take data out of variables .

Declaration of variables

JavaScript Is a weakly typed language , You don't need to specify the data type when you declare a variable , Direct use var Modifier to declare .

Variable declaration and assignment :

// Declare before assign
var a ;
a = 10;
// Declare the assignment at the same time
var b = 20;

Note on variables

(1) If you only declare and do not assign a value , Then the value of the variable is undefined.

var box;
console.log(box);

(2) Variables have to be defined before they can be used , If the variable is not declared, use ,JavaScript Will report a mistake , Tell you that the variable is undefined .

console.log(box2);

(3) It could be on the same line var Multiple variables are declared in the command .

var a, b, c = 10;
console.log(a,b,c);

(4) If you use var Redeclare an existing variable , It's invalid .

var box = 10
var box;

(5) If you use var Redeclare an existing variable and assign a value to it , That overrides the previous value

var box = 10;
var box = 25;

(6)JavaScript Is a dynamic type 、 Weak type language , in other words , There are no restrictions on the types of variables , Various types of values can be assigned .

var box = 'hello world';
box = 10;

Variable Promotion

JavaScript The way the engine works , Parse the code first , Gets all declared variables , And then run it line by line . The result of this , That's the declaration statement for all variables , Will be promoted to the head of the code , This is called a variable lift .

console.log(msg);
var msg = "so easy";

// Variable Promotion , Equivalent to the following code
var msg;
console.log(msg);
msg = "so easy";

// explain : The end result is a display undefined, Said variable msg declared , But it hasn't been assigned yet .

Be careful : Variable promotion is only for var The variables declared by the command are valid , If the variable is not used var command-declared , There will be no variable escalation .

console.log(msg);
msg = "error";

data type

although JS It's a weakly typed language , Variable has no type , But the data itself is typed . For different types , We can do different things .

JavaScript There is 6 Type of data , There are five simple data types :UndefinedNull Boolean The number and character string . A complex data type Object.

Count value (Number): Integers and decimals ( such as 1 and 3.14)
character string (String): Text made up of characters ( such as "Hello World")
Boolean value (Boolean):true( really ) and false( false ) Two specific values
Undefined:       Express “ Undefined ” Or not , That is, there is no value at present
Null:           It means a vacancy , That is, there should be a value here , But it's empty at the moment
object (object)( quote ) : A collection of values
1)、 object (object){name:”zhangsan”,age:”18”}
2)、 Array (array)[1,2,3]
3)、 function (function)function test() {}

undefined

undefined The value of the type is undefined.

undefined Is a representation of " nothing " Original value , Means that the value does not exist .

appear undefined Common situation of :

(1) When a variable is declared and not initialized , The value of this variable is undefined

var box;
console.log(box); //undefined

(2) When you call a function , This function has formal parameters , However, no actual parameters were provided , Then the parameter is undefined.

function noData(str) { // js Function parameters only need variable names
console.log(str); // undefined
}
noData(); // When calling a method , Parameter not passed

(3) When the function does not return a value , Default return undefined.

// Method does not return a value
function noData() {
console.log("Hello");
}
var re = noData();// Define methods for variables to receive no return value
console.log(re);

null

null Type is a data type with only one value , It's a special value null. It means null , That is, the value there is now empty , It represents an empty object reference .

Use Null Pay attention to the following points when type values :

1) Use typeof Operator test null return object character string .

2)undefined Derive from null, So the return value of equivalence comparison is true. Uninitialized variables and are assigned to null The variables of are equal .

console.log(undefined == null);
var box = null; // The assignment is null The variable of
var a; // Uninitialized variables
console.log(a == box); // The two values are equal

Boolean type

The boolean type has two values :true、false. It is often used to judge and loop conditions

Numerical type

The numerical type contains two kinds of values : Integer and floating point .

1) All figures ( Integer and floating point ) It's all about 64 Stored as a bit floating point number . therefore ,JS in 1 And 1.0 equal , and 1 add 1.0 It's still an integer . The highest precision of floating-point numbers is 17 Decimal place , Because floating-point operations may not be accurate , Try not to use floating-point numbers for judgment .

2) Automatically convert floating-point values that can be converted to integers when storing numeric data .

console.log(1 == 1.0); // true
console.log(1 + 1.0); // 2
var num = 8.0; // Automatically convert floating-point numbers that can be converted to integers
console.log(num); // 8

character string

Use ' ' or " " Lead up , Such as :'hello',"good".

Use the plus sign '+' String splicing , Such as :console.log('hello' + ' everybody');

object

An object is a collection of data and functions .

explain :

{}: Represents an object defined in the literal form of an object . Empty curly braces are used to define objects that contain default properties and methods .

Type conversion

Automatic type conversion

Function conversion (String to Number)

JS Provides parseInt() and parseFloat() Two global conversion functions . The former converts a value to an integer , The latter converts the value to a floating-point number . Only for String Type calls these methods , These two functions will work correctly ; For other types, it returns NaN(Not a Number).

parseInt()

Before conversion , First, the string is analyzed , Judge the position as 0 The character at , Determine if it's a significant number , If not , Then return directly NaN, Don't go on , If so, continue , Until you find the non character

parseInt("1234blue"); // returns 1234
parseInt("22.5"); // returns 22
parseInt("blue"); // returns NaN

parseFloat()

The method and parseInt() Methods are handled in a similar way , From the position 0 Start looking at each character , Until the first invalid character is found , Then put the word The string before the character is converted to a number . however , For this method , The first decimal point that appears is a valid character . If there are two decimal points , The second decimal point will be considered invalid ,parseFloat() Method will convert the string before the decimal point to a number .

parseFloat("1234blue"); // returns 1234.0
parseFloat("22.5"); // returns 22.5
parseFloat("22.34.5"); // returns 22.34
parseFloat("blue"); //returns NaN

Display conversion

Almost every number object provides toString() Function to convert content to string form , among Number Provided toString() Function to convert a number to a string .

Number It also provides toFixed() The function converts a number to a string according to the number of digits after the decimal point , rounding

// Convert content to string form
var data = 10
console.log(data.toString())

// Converts a number into a string according to the specified number of digits after the decimal point , rounding
data = 1.4;
console.log(data.toFixed(0));
data = 1.49;
console.log(data.toFixed(1));

// Not right null and undefined Use
data = null
console.log(data.toString())
data = undefined
console.log(data.toString())

JS by Number、Boolean、String Object provides a constructor , Used to cast other types of data . At this point, it's the whole data , Not part of it .

Number(false)       0
Number(true)         1
Number(undefined) NaN
Number(null)         0
Number( "5.5 ")     5.5
Number( "56 ")     56
Number( "5.6.7 ")   NaN
Number(new Object()) NaN
Number(100)         100

Boolean(""); // false – empty string
Boolean("hi"); // true – non-empty string
Boolean(100); // true – non-zero number
Boolean(null); // false - null
Boolean(0); // false - zero
Boolean(new Object()); // true – object

The last way to cast a type String() It's the simplest , Because it can convert any value into a string . To perform this cast , Just call the value passed in as a parameter toString() Method , Namely the 1 convert to "1 ", hold true convert to "true ", hold false convert to "false ", And so on . Cast to string and call toString() The only difference in the method is , Yes null or undefined Value casting can generate strings without causing errors :

var s1 = String(null); // "null"
var oNull = null;
var s2 = oNull.toString(); // won’t work, causes anerror

The simplest way to convert to a string , Directly after any data + "" that will do .

Operator

Operators are used to perform program code operations , Will operate on one or more operands .

Arithmetic operator

Operator

describe

Example

result

+

Add

x=y+2

x=7

-

reduce

x=y-2

x=3

*

ride

x=y*2

x=10

/

except

x=y/2

x=2.5

%

Mod

x=y%2

x=1

++

Self increasing ( Leading plus 、 Post derivative addition )

x=++y

x=6

--

Self reduction ( Leading minus 、 The post derivative subtraction )

x=--y

x=4

Assignment and extension operators

Operator

Example

Equivalent to

result

=

x=y

x=5

+=

x+=y

x=x+y

x=15

-=

x-=y

x=x-y

x=5

*=

x*=y

x=x*y

x=50

/=

x/=y

x=x/y

x=2

%=

x%=y

x=x%y

x=0

Comparison operator

Operator

describe

Example

==

be equal to

x==8 by false

===

Congruence ( Values and types )

x===5 by true;x==="5" by false

!=

It's not equal to

x!=8 by true

Greater than

x>8 by false

<

Less than

x<8 by true

=

Greater than or equal to

x>=8 by false

<=

Less than or equal to

x<=8 by true

Logical operators

Operator

describe

Example

&&

and

(x < 10 && y > 1) by true

||

or

(x==5 || y==5) by false

!

not

!(x==y) by true

Ternary operator

Operator

describe

Example

?:

If … otherwise …

3>5?3:5

Control statement

We wrote JavaScript The code is executed from top to bottom , Most of the time we want the code to be executed as we wish , For example, selectively executing some code , Or execute some code repeatedly , This requires the use of process control statements .

There are three kinds of flow control statements :

  1. Process execution : From top to bottom , From left to right
  2. Choose to perform : Branch selection
  3. Loop execution : repeat

choice

Single choice

if ( Conditions ){
Statement of body ;
}

First, execute the condition

If the result is true, Then execute the statement body ;

If the result is false, End if sentence .

Be careful : If there is only one sentence in the body of the statement , You can omit the braces , But it is not recommended to omit

Double choice

if ( Conditions ){
Statement of body 1;
}else {
Statement of body 2;
}

First, execute the condition

If the result is true, Then execute the statement body 1;

If the result is false, Then execute the statement body 2.

Multiple choice

if( Comparison expression 1) {
Statement of body 1;
}else if( Comparison expression 2){
Statement of body 2;
}else if( Comparison expression 3){
Statement of body 3;
}
...
[else {
Statement of body n+1;
}]

switch structure

Multiple if ...else When the value is constant ( namely === When comparing run results , The strict equality operator is used (===), Not the equality operator (==), This means that no type conversions occur when comparing .) , have access to switch Replace :

switch( expression ) {
case value 1:
Statement of body 1;
break;
case value 2:
Statement of body 2;
break;
...
default:
Statement of body n+1;
[break;]
}

break Prevent penetration , without break, Then continue to execute the following code , Until I met break Or it's all done , But sometimes penetration is used .

loop

The loop structure is used to repeat an operation Simple to understand is to repeatedly execute the same type of code , It comes in many forms .

while

Judge before you execute

The basic format
while( Judgment conditional statement ) {
Loop body statement ;
}

Extended format :
Initialization statement ;
while( Judgment conditional statement ){
Loop body statement ;
Control condition statement ; //   Without it, it's easy to form an endless loop
}

do...while

Execute before judge , At least once

The basic format
do {
Loop body statement ;
}while( Judgment conditional statement );

Extended format :
Initialization statement ;
do {
Loop body statement ;
Control condition statement ;
} while( Judgment conditional statement );

for

for( Initialization statement ; Judgment conditional statement ; Control condition statement ){
Loop body statement ;
}

Dead cycle

Conditions are always there , For ever true, There will be a life and death cycle , Here's the simplest dead loop

while(true){}
for(;;){}

break And continue

break: Stop this layer cycle

continue: Pause this cycle , Go on for the next time

Array

An array is a set of data arranged in order , The position of each value has a number ( from 0 Start ), The entire array is represented in square brackets .

To define an array

JS There are three ways to define arrays in ( You can also declare it before you assign it ):

var arr = [ value 1, value 2, value 3];  // Implicitly create

var arr = new Array( value 1, value 2, value 3); // Direct instantiation

var arr = new Array(size); // Create an array and specify the length

Basic operation

The length of the array can be determined by length Property to get , And you can change

Array name .length
Array name .length = New length

Every element in the array can be accessed and modified , Even nonexistent elements , It doesn't matter if you cross the border

Array name [ Subscript ]
Array name [ Subscript ] = The new value

Array traversal

The traversal of the array is to access each element of the array in turn ,JS Provides three ways to traverse arrays :

ordinary for Loop traversal

for(var i=0; i<= Array .length-1; i++){

}
Such as :
for(var idx=0;idx<arr.length;idx++){
console.log(arr[idx]);
}

for ... in

for(var Subscript ( Any name ) in Array name ){
Array name [ Subscript ] It's getting elements
} // Subscript ( Any name )
Such as :
for(var idx in arr){
console.log(arr[idx]);
}

forEach

Array name .forEach(function(element,index){
// element( Any name ): Elements ,index( Any name ): Subscript
})
Such as :
arr.forEach(function(elem,idx){
console.log(idx + "-->" + elem);
});

understand

Array in the use of the recommended rules to use . When storing data , From the subscript 0 Start to store array elements in order .
If the subscript :
1. Is a nonnegative integer ( Include integer strings ): Automatically from 0 Start , There is no addition undefined
2. It's a negative number 、 decimal 、 Nonnumeric string : These are not counted in length , As a " attribute " Handle , It is equivalent to a custom attribute .

Arrays are very flexible , Using array elements
1. Subscript : Non-negative integer ( Include integer strings ):
Array . Subscript
Array [ Subscript ]
2. Subscript : negative 、 decimal 、 Non numeric string :
Array [ attribute ]

  • for --> Do not traverse properties
  • foreach --> Do not traverse properties and indexes undefined
  • for in --> Don't traverse the index undefined

The operation method provided by array

Array Object provides us with some methods , You can easily manipulate arrays

push           Add elements to the end
unshift       Add elements to the front
pop           Delete the last item
shift         Delete the first item
reverse       Array flip
join           Array to string
indexOf       Array element index
slice         Intercept ( section ) Array , The original array does not change
splice         Splicing array , The original array changes , Can achieve the effect of deleting before and after
concat         Array merge

var arr = ['1','a',5,'3'];
console.log(arr);
arr.push(10);
console.log(arr);
arr.unshift('b');
console.log(arr);
arr.pop();
console.log(arr);
arr.shift();
console.log(arr);
arr.reverse();
console.log(arr);
console.log(arr.join('''));
console.log(arr);
console.log(arr.indexOf('a'));
console.log(arr.slice(2,5));
console.log(arr);
arr.splice(1,1,' One ',' Two ');
console.log(arr);
var arr1 = [0,'100'];
console.log(arr.concat(arr1));
console.log(arr);
console.log(arr1);
console.log(arr1.(arr));

function

function , That is the method . It's a pre-set function code block , It can be called repeatedly , Depending on the input parameters , Returns different values . Functions are also objects .

Definition of function

There are three ways to define functions : Function declaration statement 、 Function definition expression 、Function Constructors

Function declaration statement

function Function name ([ parameter list ]){

}
for example :
function foo(){
console.log(1);
}
foo();

The function defined in this way has the effect of declaration promotion

foo();
function foo(){
console.log(1);
}
// Variable declaration promotion
console.log( a );
var a = 2;

Function definition expression

Functions defined as expressions , The name of the function is unnecessary

var Variable name = function ([ parameter list ]) {

}
Variable name ();
for example :
var fun = function(){
console.log("Hello");
}
fun();

This method assigns an anonymous function to a variable . At this time , This anonymous function is also called function expression , Because an assignment statement can only have an expression to the right of the equal sign .

Function Constructors

Function Constructor takes any number of arguments , But the last parameter is always seen as the body of the function , The previous argument lists the parameters of the new function .

var add = new Function('x','y','return (x + y)');
// Equate to
function add(x, y) {
return (x + y);
}
add();

Be careful :

  1. js The function in is not overloaded , A function of the same name , Will be covered by the following function .
  2. js An indefinite number of parameters are allowed in , Later on arguments object

The parameters of the function 、 Calls and return sentence

Parameters

When the function is running , Sometimes you need to provide external data , Different external data leads to different results , This external data is called a parameter , The parameters defined are called formal parameters , The parameters on call are called arguments

  • Arguments can be omitted , Then the corresponding formal parameter is undefined
  • If the function parameter has the same name ( You don't usually do this ): In use, the last value shall prevail .
  • You can give the default value of the parameter : When the parameter is a special value , You can assign default values to .
  • Parameters are passed as values , Deliver a copy ; Pass the address when the reference is passed , Operate on the same object .

// When you call a function , Arguments can be omitted , Then the corresponding formal parameter is undefined
function add(a , b) {
console.log(a + "+" + b + "=" + (a + b));
}
add(3,4,5)//3+4=7
add(1);//1+undefined=NaN
add();//undefined+undefined=NaN

// If the function parameter has the same name ( You don't usually do this ): In use, the last value shall prevail
function add2(a , a) {
console.log(a);
}
add2(1,2);

// Give the parameter the default value
function defaultValue(a){
a = a || "a";
return a;
}
console.log(defaultValue());
function f(a){
// If parameter a Not for undefined or null, Then take its own value , Otherwise give a default value
(a !== undefined && a !== null) ? a = a : a = 1;
return a;
}
console.log(f());

// Value passed
var num = 12;
function change(n) {
n = 30;
}
change(num);
console.log(num);
// reference
var obj = {name: "tom"};
function paramter(o) {
o.name = 2;
}
paramter(obj);
console.log(obj.name);
// Give formal parameter o Given a new array
var obj2 = [1, 2, 3];
function paramter2(o){
o = [2, 3, 4];
o[1] = 3;
}
paramter2 (obj2);
console.log(obj2)

Function call

1. Commonly used call method

Function name ([ Actual parameters ]);

There is a return value that can be received by variables , If the receiving function has no return value undefined.

2. Function call mode

function add(a,b){
return a+b;
}
var sum = add(1,2)
console.log(sum);

3. Method call pattern

var o = {
m: function(){
console.log(1);
}
};
o.m();

return

Function execution may have a return value , Need to use return Statement to return the result to .return Statements are not required , If not , The function does not return any value , Or return to undefined.

effect :

  1. In a method that does not return a value , To end the method .
  2. Methods with return values , One is to end the method , One is to bring the value to the caller .

The scope of the function

Function scope : overall situation (global variable) and Local (local variable)

1. Global variables and local variables have the same name

var box =1; // Global variables
function display(box){
var box = 3; // here box And global variables box It doesn't matter. , there box For the parameters passed , A local variable is equivalent to a new variable
var b = 2; // local variable
console.log("box-->" + box);
}
display();
// b Cannot access
console.log("b-->" + b);

2. When you define variables in a function , If not var keyword , After use, it will automatically become a global variable

function fun(){
a = 100;
}
fun();
alert(a);

Built-in objects

Arguments   Defined only inside the function , Save the arguments of the function
Array             Array objects
Date               Date object , Used to create and retrieve dates
Math             Mathematical objects
String             String object , Provides a series of operations on strings

String

◦ charAt(idx)   Returns the character at the specified location
◦ indexOf(Chr)   Returns the location of the specified substring , From left to right . No return found -1
◦ substr(m,n)   Returns the given string from m Position start , take n Characters , If parameters n Omit , Means to get to the end of the string .
◦ substring(m,n)   Returns the given string from m Position start , To n End of position , If parameters n Omit , Means to get to the end of the string .
◦ toLowerCase()   Convert all characters in the string to lowercase .
◦ toUpperCase()   Convert all characters in the string to uppercase .
◦ length   attribute , It's not the way , Returns the length of the string .

Math

◦ Math.random()   random number
◦ Math.ceil()   Rounding up , Greater than the maximum integer
◦ Math.floor()   Round to the small , Less than the smallest integer String

Date

// Get date
◦ getFullYear()   year
◦ getMonth()   month
◦ getDate()   Japan
◦ getHours()   when
◦ getMinutes()   branch
◦ getSeconds()   second
// Setting date
◦ setYear()
◦ setMonth()
◦ setDate()
◦ setHours()
◦ setMinutes()
◦ setSeconds()
◦ toLoacaleString() Convert to local time string

explain :

  1. getMonth(): Get the value of the :0~11(1 month ~12 month )
  2. setMonth(): When the set values 0~11
  3. toLocaleString(): According to the local time Date Object to string , And return the result .

object

object (object) yes JavaScript Core concept of , It is also the most important data type .JavaScript All of the data can be treated as objects .JavaScript Provide multiple built-in objects , such as String、Date、Array wait . Objects are special data types with properties and methods .

In short , The object , It's an unordered set of data , By a number of “ Key value pair ”(key-value) constitute . adopt JavaScript We can create our own objects . JavaScript The object satisfies this kind of ” Key value pair ” We call it JSON Format , I'll see you a lot later , The great JSON object .

{ key : value , key 2: value 2,...}

Object creation

JS Create custom objects , There are three main ways : Create objects in literal form 、 adopt new Object objects creating 、 adopt Object Object's create Method to create an object .

Literal form creation

var Object name = {};// Create an empty object
var Object name = { key : value , key 2: value 2,...}

var obj = {
'name' : 'hello',
age : 12,
sayHello : function () {
console.log(" I'm the method in the object ");
},
courses : {
javase : 4,
javascript : 3
},
isLike : true,
members : [
{name : " Xiaohong ",age : 20},
{name : " Little green ",age : 22},
{name : " Small blue ",age : 27},
{name : " Xiao Huang "}
]
};

adopt new Object establish

var Object name = new Object(); // Create an empty object

var obj = new Object();
obj.name = 'zs';
obj.age = 18;
console.log(obj);

adopt Object Object's create Method creation

var Object name = Object.create(null);
var obj = Object.create(null);
obj.name = 'ls';
obj.gender = true
console.log(obj);

var objn = Object.create(obj);
objn.age = 18;
console.log(objn);
console.log(objn.gender)

Serialization and deserialization of objects

Serialization is about to JS Objects are serialized as strings , Deserialization is to deserialize a string to JS object .JS By calling JSON Method , You can sequence objects into strings , You can also deserialize strings into objects .

// Serializing objects , Convert object to string
JSON.stringify(object);

// Deserialization , Will a Json String to object .
JSON.parse(jsonStr);

this

this yes JavaScript A key word of language .

It represents the function runtime , An internal object generated automatically , Can only be used inside a function .

As the function is used in different situations ,this The value of will change . But there is a general principle , That's it this refer to , The object that called the function .

Use... In functions this

Use... In functions this It's a global call , Represents a global object , adopt window Object to access .

function test () {
this.x = 1;
console.log(this.x);
}
test();
console.log(x); // Equivalent to a property defined on a global object

var x = 10;
console.log(x)  // 10
function test (){
console.log(this.x)  // 10
this.x = 1;
console.log(this.x) // 1
console.log(this)
}

test();
console.log(x); // 1
console.log(this);

Use in objects this

Functions in objects use this, Represents the current superior object .

var obj = {
name : ' Zhang San ',
age : 20,
sayHello : function () {
console.log(this.name)
console.log(this)
}
}
obj.sayHello();

版权声明
本文为[Love to program]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210122165409132D.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云