A comprehensive collection of common JavaScript Functions and a collection of javascript Functions

Source: Internet
Author: User

A comprehensive collection of common JavaScript Functions and a collection of javascript Functions

This article mainly summarizes common JavaScript functions, such as some common JavaScript objects, basic data structures, function 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 Functions
  • Rich Web interfaces
  • Local or remote storage.
  • Implements front-end components of distributed network applications and manages data storage in the background.
  • JavaScript can be used to implement a complete distributed Web application.

I. Data Types in JavaScript

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

Provides five basic reference types:Object, Array, Function, Date and RegExp. Arrays, functions, dates, and regular expressions are special types, but strictly speaking, date and regular expressions are metadata types and can be encapsulated in other objects.

In JS, the variable type, array element type, function parameters, and return value types do not need to be declared. conversions between types are automatically executed.

The variable value can be:

  • 1. Value: such as a string, number, or Boolean value.
  • 2. Object Reference: a typical object, Data, function, date, or regular expression can be referenced.
  • 3. Special data value, Null, is a typical default value for object initialization.
  • 4. Special Data undefined, often used for variables that have been defined but are not assigned a value.

String is a series of Unicode strings, such as "hello world", "A3FO", or an empty String "". string connections can be executed using the + operator, you can also use "=" to verify whether two strings are equal;

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

Numeric indicates a 64-bit floating point number. In JS, there is no obvious distinction between integer and floating point number. If the value of an expression is not equal to a number, its value can be set to NaN, indicating that it is not a number, it can be used together with isNaN.
The following table shows detailed type tests and conversions.

II. Scope of Variables
Currently, JavaScript and ES5 provide two types of scopes: global variables and function scopes without block scopes. The range of block scopes is not clear, so use of block Scopes should be avoided. The following code, despite being a common Pattern by developers, is a trap.

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

It is best to declare all variables at the beginning of the function. In JS and ES6 versions, block scopes are supported and variables are defined using the keyword "let.

Strict Mode)
Starting from ES5, the strict mode is used to detect running errors. In the strict mode, all variables must be declared. If you assign a value to an undeclared variable, an exception is thrown.

In a JavaScript file or <Script> element, enter the following code to switch to the strict mode:

Use strict;
Strict mode is recommended unless the library on which the project depends is not compatible with the strict mode.

Multiple objects
Objects in JS are different from objects in OO or UML. Especially in JS, objects do not need to be instantiated. They can also have their own methods, including not only property slots, but also method slots. The key-value slots are also included. Therefore, they have three Slots in total, and common objects only have attribute slots.

JS objects are slots composed of a series of name-values. The name can be the property name, function name, And ing 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 the Slot name is a valid JS identifier, the Slot can represent attributes, methods, or key-value pairs. If the name contains special characters such as spaces, the Slot represents a key-value pair, which is a ing element, as follows:

Name in Property Slot:

1. data value Attribute. In this case, Value indicates the variable value or Value expression.

2. object-valued attribute. Value indicates the object reference or object expression.

Method Slot indicates the JS function, and its value is the JS Function Definition expression:

Object Attributes can be accessed in two ways:

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

person1.lastName = "Smith"

2. Use map:

person1["lastName"] = "Smith"

JS objects can be used in various ways.Five common cases:

1. Record is a set of Property slots, such:

var myRecord = {firstName:"Tom", lastName:"Smith", age:26}

2. map, such as Hash map, array, and hash table;

var numeral2number = {"one":"1", "two":"2", "three":"3"}

3. The Untyped object does not need to be instantiated. 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, which is accessed by array subscript. For example, array initialization:

Var a = [1, 2, 3];
JS Arrays can be dynamically increased, so the array index may have more than the actual number of elements, as shown below:

A [4] = 7;
Array loop:

For (I = 0; I <a. length; I ++ ){...}

Arrays are special object types. Therefore, in many cases, you need to determine whether the variable is of the Array type. Use the IsArray method: Array. isArray ().

Add new elements to the array:

A. push (newElement );
Delete:
A. splice (I, 1 );
Search:
If (a. indexOf (v)>-1 )...
Loop:

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);

3. Maps
Map provides key-to-value ing. 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"}

Added:
MyTranslation ["my car"] = "mein Auto ";
Delete:
MyTranslation ["my car"] = "mein Auto ";
Search:
If ("my bike" in myTranslation )...
Loop:
Var I = 0, key = "", keys = [];
Keys = Object. keys (m );
For (I = 0; I <keys. length; I ++ ){
Key = keys [I];
Console. log (m [key]);
}
If map is small, you can use the foreach statement:
Object. keys (m). forEach (function (key ){
Console. log (m [key]);
})
Copy map
Var clone = JSON. parse (JSON. stringify (m ))
Summary:JavaScript supports four basic data structures.
1: array lists: for example, ["one", "two", "three"], special JS object

2: records: Special JS objects, such as {firstName: "Tom", lastName: "Smith "};

3: maps: for example, {"one": 1, "two": 2, "three": 3}

4: entity table: as shown in the following table, it is a special map with a fixed ID.

There is no obvious distinction between record, map, and entity in actual application, but it is a conceptual distinction. JS engines are all objects. However, they are conceptually differentiated.

Iv. Functions
As shown in table 1, a function is a special JS object. The name and length attributes indicate the number of parameters. For example, to determine whether v points to a function:

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

Function Definition:

var myFunction = function theNameOfMyFunction () {...}

TheNameOfMyFunction is optional. If the function name is omitted, it is called an anonymous function. Generally, a function is called through a variable. The code above indicates

MyFunction calls myFunction () instead of theNameOfMyFunction.

Anonymous function expressions are called lambda expressions in other programming languages. The following code is an anonymous function. It can be compared with the predefined sort function:

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 () {...}

And code

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

Equivalent;

Declares the theNameOfMyFunction function and uses the theNameOfMyFunction variable to reference the function.

JS provides function inline, And the closure mechanism allows JS functions to call variables other than functions. Function can create closure to store the current environment. As follows, you do not need to pass the external variable results to the internal function through parameters. It is available in itself.

var sum = function (numbers) { var result = 0; numbers.forEach( function (n) { result += n; }); return result;};console.log( sum([1,2,3,4]));

When executing a method, you can use the built-in arguments object to access the parameters in the function. The arguments object and the array use method are similar, with the Length attribute and index, in addition, you can use the For statement to iterate cyclically. However, because it is not an Array instance, some methods of JS arrary cannot be applied, such as foreach.

The number of elements in the arguments object is the same as the number of function parameters. You can also define a method without specifying the number of parameters. You can assign multiple parameters to the function during the call, for example:

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

Methods are defined on the constructor prototype. They can be called by the constructor created by the object, such as Array. prototype. forEach; Array indicates the constructor, And the instance of the calling class serves as the context object reference. In foreach, numbers indicates the context object:

var numbers = [1,2,3]; // create an instance of Arraynumbers.forEach( function (n) { console.log( n);});

Whether the prototype method is called by the context object or not, the Call method of the js function can be used to Call the object as long as the parameter is an object. We can use the foreach loop method as follows:

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

Function. prototype. call and apply both exist to change the context when a Function is running.

5. Define and use classes
Class is a basic concept in object-oriented systems, and Object Instantiation is called a class. Classes defined in JS must meet the following five requirements:

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

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

3. instance-level attributes are used to detect the direct type of objects.

4. property inheritance

5. Method inheritance.

In addition, it also supports integration and multiclass classification.

There is no uniform definition specification for classes in JS. You can use different code modes to define classes and apply them to different frameworks. The method for defining the most common classes in JS is as follows:

1. constructor specification, which can be inherited through the prototype chain implementation method and support creating new class instances.

2. factory Object, used to predefine the Object. create method to create a new instance. In this method, the Inheritance Mechanism Based on constructors can be replaced by other mechanisms.

Classes are required to create an App. Therefore, you often need to define the relationships between classes. Therefore, you must ensure that the same class is used.

6. Constructor-based classes
Only ES6 introduces classes that define constructors. The new syntax supports defining some simple class inheritance steps as follows:

Step 1.a base class Person has two attributes: first Name and Last Name. The method toString at the instance layer and the static method checkLastName;

class Person { constructor( first, last) { this.firstName = first; 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 step 2, a subclass with other attributes and methods is defined, and the related methods of the parent class may be overwritten:

class Student extends Person { constructor( first, last, studNo) { super.constructor( first, last); this.studNo = studNo;  } // method overrides superclass method toString() { return super.toString() + "(" + this.studNo +")"; }}

In ES5, you can define sub-classes that inherit the constructor class. As follows:

Step 1.a first defines the constructor, which can implicitly define class attributes and assign values;

function Person( first, last) { this.firstName = first;  this.lastName = last; }

Note: this in the above Code refers to the newly generated object. When the constructor is called, this object is generated.

Step 1. B defines the instance layer:

Person.prototype.toString = function () { return this.firstName + " " + this.lastName;}

Step 1.c defines static methods:

Person.checkLastName = function (ln) { if (typeof(ln)!=="string" || ln.trim()==="") { console.log("Error: invalid last name!"); }}

Step 1.d define static attributes of the class hierarchy

Person.instances = {};

Step 2.a defines the subclass:
1: function Student (first, last, studNo ){
2: // invoke superclass constructor
3: Person. call (this, first, last );
4: // define and assign additional properties
5: this. studNo = studNo;
6 :}
Create an object by calling the super class constructor Person. call (this. This indicates Student. Property Slots has created (firstName and lastName) and other subclass-related attributes in the constructor of the superclass. In this case, you can use the Property Inheritance mechanism to ensure that all attributes have been defined and created.

Step 2b: Install method inheritance through the prototype attribute of the constructor. As follows, a new object is assigned to create the Prototype attribute of the subtype constructor and make appropriate adjustments:

// Student inherits from PersonStudent.prototype = Object.create(  Person.prototype);// adjust the subtype's constructor propertyStudent.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 constructor class-based instantiation is created by applying the new operator and providing the appropriate constructor parameters:

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

The toString method is called through pers1:

alert("The full name of the person are: " +  pers1.toString()); 

In JS, prototype is an object with method slots and can be inherited through JS methods or attribute slots.

7. Factory-based classes
The JS Object Person is defined in this method. It contains special Create methods to call the predefined Object. Create method to Create objects of the Person type;

var Person = { name: "Person", properties: { firstName: {range:"NonEmptyString", label:"First name",  writable: true, enumerable: true}, lastName: {range:"NonEmptyString", label:"Last name",  writable: true, enumerable: true} }, methods: { getFullName: function () { return this.firstName +" "+ this.lastName;  } }, 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] = slots[prop]; }) return obj; }};

Note that the actual JavaScript Object Person represents the factory-based class. The factory-based class is instantiated by calling its own Create method:

Var pers1 = Person. create ({firstName: "Tom", lastName: "Smith "});
The getFullName method is called through pers1., as follows:

Alert ("The full name of the person are:" + pers1.getFullName ());
Each attribute declaration is declared using Object. Create, which contains three parameters and values: 'scriptors' writable: true and enumerable: true; as shown in the preceding five rows.

Is it a very good article? Just add it to favorites!

Articles you may be interested in:
  • Summary of common javascript Functions
  • Summary of common javascript Functions

Related 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.