A very comprehensive set of JavaScript common feature summary _javascript tips

Source: Internet
Author: User
Tags closure data structures function definition

This paper summarizes the common functions of javascript, such as some commonly used JS objects, basic data structure, functional functions, and some common design patterns.

Directory:

As we all know, JavaScript is a dynamic object-oriented programming language that can achieve the following effects:

    • Rich Web page Features
    • Rich Web Interface
    • Implement local or Remote storage.
    • Realize the front-end component of distributed network application and manage data storage in the background.
    • Use JavaScript to achieve a complete distributed Web application.

Data types in JavaScript

JavaScript provides three types of metadata,String,number, and Boolean, you can use typeof (V) to test the type of variable V, typeof (v) = = "Number"

Provides five basic types of references:Object, Array, Function, Date, and RegExp. arrays, functions, dates, and regular expressions are special types, but strictly speaking, date and regular expressions are meta data types and can be encapsulated in other objects.

In JS, variable types, array element types, function arguments, and types of return values do not need to declare types, and conversions between types are performed automatically.

The value of the variable can be:

    • 1. Numeric values: such as strings, numbers, or Boolean values.
    • 2. Object reference: You can reference a typical object, or it can be a data, function, date, or regular expression.
    • 3. Special data value, Null, is a typical default value for initializing an object.
    • 4. Special data undefined, often used in variables that have been defined but not assigned.

A string is a series of Unicode strings, such as "Hello World", ' a3fo ' or an empty string ', which can be executed by the + operator or by using the = number to verify that two strings are equal;

if (firstName + lastName = = "James Bond") ...

Numeric represents 64-bit floating-point number, in JS there is no obvious distinction between shaping and floating-point number, if the value of an expression is not equal to a digit, then its value can be set to Nan, indicating Non-numeric, can be combined isNaN use.
The following table is a detailed type test and conversion

Ii. scope of the variable scopes
Currently, JAVASCRIPT,ES5 provides two types of scopes: global variables and function scopes, no block scopes. Block scopes are less explicit, so you should avoid the use of block scopes. The following code, though a common pattern for developers, is a trap.

function foo () {for
 (var i=0 i < i++) {
 ...//do something with I
 }
}

All variable declarations are best at the beginning of a function. Block scopes are supported in the JS,ES6 version, with keyword let to define variables.

Strict model (Strict mode)
starting with ES5, strict mode is used to detect run-time errors, in strict mode, all variables must declare that assigning an undeclared variable throws an exception.

Within the JavaScript file or <Script> element, switch to strict mode by entering the following code:

Use strict;
Strict mode is recommended unless the library on which the project relies is incompatible with strict mode.

Multiple objects
JS In the object concept is different from OO or UML objects, especially in JS objects do not need to instantiate, can also have their own methods, not only the property slots, also contains method slots. It also contains key-value slots, so they have a total of three kinds of slots, while the common object is only the property slot.

JS object is a series of name-value composed of slot. Name can be the property name, the function name, and the mapping name. objects can be created in a specific way, using the JS Object declaration syntax (JSON) without instantiating a class. The code is as follows:

var Person1 = {lastName: "Smith", FirstName: "Tom"};
var O1 = object.create (null); An empty object with no slots

If slot's name is a valid JS identifier, then slot can represent a property, method, or key-value pair. If the name contains some special character Furu spaces, the slot represents a key-value pair and is a mapping element, as follows:

Name in the property Slot:

1. The data Value property, in which case value represents a variable value or a value expression.

2. Object-valued property, Value represents an object's reference or an object expression.

Method Slot is the JS function, and its value is the JS function definition expression:

The Object property can be accessed using two methods:

1. Use "." (Similar to C + + and Java):

Person1.lastname = "Smith"

2. Use map:

person1["lastName"] = "Smith"

JS objects can be used in a variety of ways, following are Five common scenarios:

1. The record is a collection of property slots, such as:

var Myrecord = {firstName: "Tom", LastName: "Smith", age:26}

2. Map such as hash map, array, hash table;

var numeral2number = {"One": "1", "Two": "2", "Three": "3"}

3. The untyped object does not need to instantiate the class, it may contain the property slot and function slots:

var Person1 = { 
 lastName: "Smith", 
 firstName: "Tom",
 getfullname:function () {return
 This.firstname + " "+ This.lastname; 
 } 
;
Array List

JS array is the logical data structure, accessed through the array subscript. To initialize an array of arrays:

var a = [1,2,3];
JS arrays can grow dynamically, so the array index may be more than the actual number of elements, as follows:

A[4] = 7;
Array Loop:

for (i=0 i < a.length; i++) {...}

Arrays are special object types, so there are many cases where you need to determine whether a variable is an array type, using the IsArray method: Array.isarray (a).

Add new element to array:

A.push (newelement);
Delete:
A.splice (i, 1);
Find:
if (A.indexof (v) >-1) ...
Cycle:

var i=0;
for (i=0 i < a.length; i++) {
 console.log (a[i]);

If the array is small, you can use the Foreach Loop:

A.foreach (function (elem) {
 console.log (elem);
}) 

JS also provides functions for cloning arrays:

var clone = a.slice (0);

Third, Maps
map provides key to worthwhile mapping. JS map is a string of character sets that can contain spaces:

var mytranslation = { 
 ' my house ': ' Mein Haus ', 
 ' my boat ': ' Mein Boot ', 
 ' My horse ': ' Mein Pferd '
}

Increase:
mytranslation["My Car" = "mein Auto";
Delete:
mytranslation["My Car" = "mein Auto";
Find:
if (' My bike ' in mytranslation) ...
Cycle:
var i=0, key= "", keys=[];
Keys = Object.keys (M);
for (i=0 i < keys.length; i++) {
key = Keys[i];
Console.log (M[key]);
}
If the map is smaller, you can use a foreach statement:
Object.keys (M). ForEach (function (key) {
Console.log (M[key]);
})
Copy Map
var clone = Json.parse (Json.stringify (m))
Summary: JavaScript supports 4 basic data structures.
1:array lists: such as ["One", "two", "three"],special JS object

2:records: Special JS object, such as {firstName: "Tom", LastName: "Smith"};

3:maps: such as {"One": 1, "two": 2, "three": 3}

4:entity table: The following table shows a special map with a fixed ID record.

There is no obvious distinction between the record,map,entity in practical application, but the conceptual distinction. For the JS engine, are objects. But conceptually there is a distinction.

Four, function
As shown in table 1, functions are special JS objects, with the name attribute and the Length property representing the number of parameters, as follows, to determine whether V is pointing to a function:

if (typeof (v) = = "function") {...}

function definition:

var myfunction = function thenameofmyfunction () {...}

Thenameofmyfunction is optional, and if the function name is omitted, the function is called an anonymous function. Typically, a function is called by a variable, such as the code above, which means

MyFunction calls the MyFunction () function instead of using thenameofmyfunction ().

An anonymous function expression is called a lambda expression in other programming languages. The following code is an anonymous function. You can compare the predefined sort functions:

var list = [[1,2],[1,3],[1,1],[2,1]]; 
List.sort (function (x,y) {return 
 ((x[0) = = Y[0])? X[1]-y[1]: x[0]-y[0]);

function declaration:

function thenameofmyfunction () {...}

With the Code

var thenameofmyfunction = function thenameofmyfunction () {...}

Equivalent

Declares the function thenameofmyfunction and uses the thenameofmyfunction variable to refer to the function.

JS provides function inline, the closure mechanism allows the JS function to call functions outside the use of variables. Functions can create closure to store the current environment. as follows, you do not need to pass the result of an external variable to an intrinsic function by using a parameter, which is itself available.

var sum = function (numbers) {
 var result = 0;
 Numbers.foreach (function (n) {result
 = n;
 });
 return result;
};
Console.log (sum ([1,2,3,4]));

When you execute a method, you can use the built-in arguments object to access the parameters within the function, the arguments object is similar to the array usage, has the length attribute, also has the index, and can use the For statement to loop the iteration. However, because it is not an array instance, some of the methods of JS Arrary cannot be applied like foreach.

The arguments object has the same number of elements as a function parameter, or you can define a method without specifying the number of arguments, and when invoked, you can assign multiple parameters to a function, such as:

var sum = function () {
 var result = 0, i=0;
 for (i=0 i < arguments.length. i++) {Result
 = result + Arguments[i];
 }
 return result;
};
Console.log (sum (0,1,1,2,3,5,8)); 20

The method is defined on the stereotype of the constructor, which can be called by the constructor created by the object, such as the Array.prototype.foreach;array representation constructor, and the instance of the class is invoked as a context object reference, as follows: Numbers represents a context object in foreach:

var numbers = [1,2,3]; Create an instance of Array
Numbers.foreach (function (n) {
 console.log (n);
});

Whether a prototype method is invoked by a context object, but as long as the argument is an object, you can use the call method of the JS function to aid the calling object. As follows, we can use the Foreach Loop method:

var sum = function () {
 var result = 0;
 Array.prototype.forEach.call (arguments, function (n) {result
 = result + N;
 });
 return result;
};

Both the Function.prototype.call method and apply are meant to change the context of a function at run time.

V. Definition and use of classes
Classes are the basic concepts of object-oriented objects, which are instantiated as classes. The definition class in JS needs to meet the following five requirements:

1. Specify the class name, instance-level properties and methods, class-level properties, and methods.

2. Is a predictable strength that can be used to verify whether an object is an instance.

3. Instance-level properties are used to detect the direct type of an object.

4. Property inheritance

5. Method inheritance.

In addition to the support for the OH Integration and multiple classification.

There is no uniform definition specification for classes in JS, you can use different code patterns to define classes, and apply them to a variety of different frameworks. The most common way to define classes in JS is as follows:

1. Constructor specification, you can implement method inheritance through prototype chain, and support the creation of new class instances.

2. Factory object, used for predefined object.create methods to create new instances. The inheritance mechanism based on constructors in this method can be replaced by other mechanisms.

Creating an app requires classes, so it's often necessary to define relationships between classes, so it's important to ensure that you use the same

Vi. constructor-based Classes
Only ES6 introduces a class that defines a constructor based. The new syntax supports the definition of some simple class inheritance, as follows:

Step 1.a the base class person has two attributes, first name and last name, the instance layer's method tostring and static method Checklastname;

Class Person {
 constructor (I, last) {
 this.firstname = i;
 This.lastname = Last;
 }
 ToString () {return
 This.firstname + "" +
 This.lastname;
 }
 Static Checklastname (LN) {
 if (typeof (LN)!== "string" | | 
 Ln.trim () = = "") {
 Console.log ("Error:" +
  "Invalid last name!")
 ;
 }
}

Step 1.b class-level attribute definition:

Person.instances = {};
In the second step, you define a subclass with other properties and methods, or you can override the parent class's related methods:

Class Student extends Person {
 constructor (i, last, Studno) {
 super.constructor (i, last);
 This.studno = Studno; 
 }
 Method overrides superclass Method
 toString () {return
 super.tostring () + "(" +
 This.studno + ")";
 }
}

ES5, you can define subclasses that inherit based on the constructor class. As follows:

STEP1.A first defines the constructor function, which can implicitly define the properties of the class and assign the value;

function person (i, last) {
 this.firstname = i; 
 This.lastname = last; 
}

Note that this in the preceding code refers to the newly generated object, which is already generated when the constructor is called.

Step1.b the method of defining the instance layer:

Person.prototype.toString = function () {return
 This.firstname + "" + This.lastname;
}

Step 1.c defines a static method:

Person.checklastname = function (LN) {
 if typeof (LN)!== "string" | | Ln.trim () = = "") {
 Console.log ("Error: Invalid last name! ");
 }
}

Step 1.d defines static properties for class hierarchies

Person.instances = {};

Step 2.a Define subclasses:
1:function Student (A, last, Studno) {
2://Invoke Superclass constructor
3:person.call (This, a, last);
4://define and assign additional properties
5:this.studno = Studno;
6:}
Create a new object by calling the constructor of the superclass Person.call (this, ...). Where this refers to a property that Student,property slots has created (FirstName and LastName) and other subclass-related properties in the superclass constructor. In this case, you can use the property inheritance mechanism to ensure that all attributes have been defined and created.

STEP2B, install method inheritance through the prototype property of the constructor. As follows, a new object is assigned to create the prototype property of the subtype constructor and the appropriate adjustments are made:

Student inherits from person
Student.prototype = object.create ( 
 person.prototype);
Adjust the subtype ' s constructor property
Student.prototype.constructor = Student;

STEP2C, redefine the subclass method to override the superclass method:

Student.prototype.toString = function () {return
 Person.prototype.toString.call (this) +
 "(" + This.studno + ")" ;
};

The instantiation based on the constructor class is created by applying the new operator and provides the appropriate construction parameters:

var pers1 = new Person ("Tom", "Smith");

Method ToString passes through the pers1. To invoke:

Alert ("The full name of the person are:" + 
 pers1.tostring ());
 

In JS, prototype is an object that has method slots, which can be inherited through JS methods or property slots.

Seven, based on the factory class
in this method, the JS object person is defined, and the special create method is used to invoke the predefined Object.create method to create the object of person type.

var person = {
 name: ' Person ',
 properties: {
 firstName: {range: ' nonemptystring ', Label: ' Name ' 
 , Writable:true, enumerable:true},
 lastName: {range: "nonemptystring", Label: "Last Name", 
 Writable:true, Enumerable:true}
 },
 methods: {
 getfullname:function () {return
 This.firstname + "" + this.lastname;< c11/>}
 },
 create:function (slots) {
 //Create object
 var obj = object.create (This.methods, this.properties);
 Add special property for *direct type* of Object
 object.defineproperty (obj, "type", 
 {value:this, writable: False, Enumerable:true});
 Initialize Object
 Object.keys (slots). ForEach (function (prop) {
 if (prop in this.properties) obj[prop] = Slo Ts[prop];
 })
 return obj;
 }
;

Note that the JS object person actually represents the Factory-based class. The instantiation of the Factory-based class is implemented by invoking its own create method:

var pers1 = person.create ({firstName: "Tom", LastName: "Smith"});
The Getfullname method is through pers1. Called, as follows:

Alert ("The full name of the person are:" + pers1.getfullname ());
The declaration of each attribute is declared using Object.create, which contains three parameters and values, ' descriptors ' writable:true and enumerable:true, as in line fifth above.

is not a very good article, resolute Collection!

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.