|
This paper summarizes the JavaScript commonly used functions are summarized, as some commonly used amount JS objects, the basic data structure, function and other functions, there are some common design patterns.
table of Contents:
As we all know, JavaScript is a dynamic object-oriented programming language that can achieve the following effects:
1. rich Web pages function
2. rich Web interface
3. Local or remote storage.
4. The realization of front-end components of distributed network applications, and data storage management in the background.
5. Using JavaScript can achieve a complete distributed Web applications.
JavaScript data types
JavaScript provides three types of metadata, string, number, and Boolean, you can use typeof (v) test variable V type, typeof (v) === "number"
It offers five basic reference types: Object, Array, Function, Date and RegExp. Arrays, functions, date and regular expressions is a special type, but strictly speaking, the date and regular expressions are primitive data types, can be encapsulated in other objects.
JS variable type conversion array element type, and the type of function parameters do not need to declare the type of return value types are automatically performed.
Variable values can be:
1. Value: such as strings, numbers, or Boolean value.
2. The object reference: typical objects that can be referenced, it can be data, functions, date or a regular expression.
3. Special data value, Null, is a typical default value used to initialize the object.
4. Special Data undefined, commonly used have been defined, but the assignment of variables.
string is a sequence of Unicode strings, String, such as "hello world", 'A3FO' or an empty string, "", string concatenation can be performed by the + operator can also be used to verify the = sign two strings are equal ;
if (firstName + lastName === "James Bond") ...
64-bit floating-point numeric representation, there is no clear distinction between shaping and float in JS, if the value of an expression is not equal to a certain number, then its value is set to NaN, represents a non-digital, can be combined isNaN use.
Scoped variables
Currently, JavaScript, ES5 provides two types of scopes: global variables and function scope, no block scope. Range block scope is not clear, it should avoid the use of block scope. The following code, though developers commonly Pattern, but it is a trap.
function foo () {for (var i = 0; i <10; i ++) {
... // Do something with i
}
}
All variable declarations are the best starting position in the function. Support block scope in JS, ES6 releases, keyword-let-defined variables.
Strict mode (Strict Mode)
From the beginning ES5 strict mode is used for error detection when run in strict mode, all variables must be declared, if the undeclared variable assignment will throw an exception.
In a JavaScript file or a < Script > element, by entering the following code to switch to the strict mode:
use strict;
It recommended strict mode, unless the project dependent libraries are not compatible strict mode.
Variety of objects
JS objects concept is different from OO or the UML object, especially in JS objects do not need to instantiate can also have their own methods, not only the property slots, also contains method slots. In addition also contains key-value slots; therefore they are a total of three Slots, and common objects only attribute slot.
JS object is a Slot by a series of name-value thereof. The name may be the attribute name, function name, map name. Objects can be created in a particular way, using JS object declaration syntax (JSON), without the need to instantiate a class. Code is as follows:
var person1 = {lastName: "Smith", firstName: "Tom"};
var o1 = Object.create (null); // an empty object with no slots
If the name is lawful Slot JS identifier, Slot may represent properties, methods, or pairs. If the name contains some special characters such as space, the Slot on behalf of key-value pair is a map element, as follows:
Property in Slot name:
1. data value property, in this case, Value value of the variable, or the value of the expression.
2. object-valued attribute, Value representing an object reference or object expression.
method Slot is represented by JS function, its value is JS function definition expression:
Object properties can be accessed in two ways:
1. Use (similar to C ++ and Java). "":
person1.lastName = "Smith"
2. Using the map:
person1 [ "lastName"] = "Smith"
JS objects can be used in a variety of ways, the following are five common situations:
1. Record Property slots are set, such as:
var myRecord = {firstName: "Tom", lastName: "Smith", age: 26}
2. map as Hash map, array, hash table;
var numeral2number = { "one": "1", "two": "2", "three": "3"}
3. Untyped object does not need to instantiate the class, it may contain a property slot and function slots:
var person1 = {
lastName: "Smith",
firstName: "Tom",
getFullName: function () {return this.firstName + "" + this.lastName;
}
};
Array List
JS array or logical data structure by array subscript access. Array initialization:
var a = [1,2,3];
JS array of dynamic growth, the array index is likely more than the number of actual elements, as follows:
a [4] = 7;
Array Cycle:
for (i = 0; i
An array is a special type of object, it is in many cases, need to determine whether a variable is an array type, use IsArray method: Array.isArray (a).
Add a new element to the array:
a.push (newElement);
delete:
a.splice (i, 1);
Find:
if (a.indexOf (v)> -1) ...
cycle:
var i = 0;
for (i = 0; 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 an array of functions cloning:
var clone = a.slice (0);
Maps
map provides key mappings to be worth. JS map is a string of characters, and may 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
key = keys [i];
console.log (m [key]);
}
If the 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 support four basic data structures.
1: array lists: such as [ "one", "two", "three"], special JS objects
2: records: JS special objects, such as {firstName: "Tom", lastName: "Smith"};
3: maps: such as { "one": 1, "two": 2, "three": 3}
4: entity table: the table below, is a special map, there is a record value of fixed ID.
record, map, entity there is no clear distinction in practice, only a conceptual distinction between. Of the JS engine, it is an object. But there is a distinction between the concept.
function
As shown in Table 1, the function is a special JS object that has name attribute and length attribute indicates the number of parameters, as follows, to determine whether the pointing function v:
if (typeof (v) === "function") {...}
Function definition:
var myFunction = function theNameOfMyFunction () {...}
theNameOfMyFunction is optional, if the function name is omitted, the function is called anonymous function. Typically, the function is invoked by variables, such as the above code, then
myFunction will call myFunction () function, rather than using theNameOfMyFunction () call.
Anonymous function expression called lambda expressions in other programming languages. The following code is an anonymous function. With predefined sort function comparison:
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 Codes
var theNameOfMyFunction = function theNameOfMyFunction () {...}
equivalence;
Declare the function theNameOfMyFunction, and use theNameOfMyFunction variable to reference the function.
JS provides function inlining, closure mechanism allows the use of variable JS function calls outside the function. You can create a function closure to store the current environment. Below, the parameter is not required by the results of external variables passed to an internal function, which itself is available.
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 parameter object to access the built-in arguments inside the function, arguments object is similar to an array using the method, it is the length of the property, there is also an index, and you can use the For statement to loop iteration. However, because it is not an Array instance, some of the methods can not be applied, such as JS arrary foreach.
arguments object is the number of elements with the same number of function parameters can also be defined method when you do not specify the number of parameters, when you call, you can assign a function of several parameters, such as:
var sum = function () {
var result = 0, i = 0; for (i = 0; i
result = result + arguments [i];
} Return result;
};
console.log (sum (0,1,1,2,3,5,8)); // 20
The method is in the prototype constructor defined constructor can create an object by calling, as Array.prototype.forEach; Array represents the constructor, call the class as an instance of the context object reference as follows: The numbers indicate the context in foreach Object:
var numbers = [1,2,3]; // create an instance of Array
numbers.forEach (function (n) {
console.log (n);
});
Regardless of whether the method is called a prototype context object, but as long as the parameter is an object, you can use the Call method JS function to assist the calling object. Below, 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;
};
Function.prototype.call methods and are intended to apply to change the context of a function is running, that the context exists.
Definition and use of classes
Object-oriented class is the basic concept of object called a class is instantiated. JS defined class must meet the following five demands: 1. Specify the name of the class, instance-level properties and methods, class-level attributes and methods. 2. predictable strength, can be used to verify whether it is an instance of an object. 3. Examples of level attributes for the direct detection of the type of the object. 4. The method inherited property inheritance.
Oh, in addition to support for integrated and multi-classification.
JS in a class there is no uniform definition of specifications, you can define a class using a different code patterns, and applied to a variety of different frameworks. The most common method JS class defined as follows:
1. constructor specification, implementation inheritance through prototype chain, and supports the creation of a new instance of the class.
2. factory object used Object.create predefined method to create a new instance. It can be replaced by other mechanisms, the method based on inheritance constructor.
Create App need to use class, so often need to define the relationships between classes, it is necessary to ensure the use of the same class
Constructor-based classes
Only ES6 definition is based on the introduction of the class constructor. The new syntax supports the definition of some simple class inheritance, follow these steps:
Step 1.a base Person class has two properties, first Name and Last Name, static methods and instance methods toString layer 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 hierarchy attribute definitions:
Person.instances = {};
In the second step, we define a subclass with other properties and methods, but also possible to rewrite the relevant parent class:
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 + ")";
}
}
ES5, you can define inheritance based child class constructor class. as follows:
Step1.a first define constructor can attribute implicit class definition and assignment;
function Person (first, last) {this.firstName = first;
this.lastName = last;
}
Note that the above code this refers to the object newly generated when the constructor is called, the object has been generated.
Step1.b instance method defined layers:
Person.prototype.toString = function () {return this.firstName + "" + this.lastName;
}
Step 1.c define static methods:
Person.checkLastName = function (ln) {if (typeof (ln)! == "String" || ln.trim () === "") {
console.log ( "Error: invalid last name!");
}
}
Step 1.d defined class hierarchy static properties
Person.instances = {};
Step 2.a defined subclasses:
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:}
Person.call by calling the constructor of the superclass (this, ...), to create a new object. This means that where the Student, Property Slots in the superclass constructor has been created ((firstName and lastName) as well as other sub-categories related properties. In this case, you can use Property Inheritance mechanism to ensure that all the attributes have been defined and It is created.
Step2b, property installation method inheritance through prototype constructor. Below, assign a new object is created subtype constructor Prototype properties, and make appropriate adjustments:
// Student inherits from PersonStudent.prototype = Object.create (
Person.prototype); // adjust the subtype's constructor propertyStudent.prototype.constructor = Student;
Step2c, redefined subclass method overrides the superclass method:
Student.prototype.toString = function () {return Person.prototype.toString.call (this) + "(" + this.studNo + ")";
};
Based on an example of the class's constructor is through the application of new operator to create and provide the appropriate configuration parameters:
var pers1 = new Person ( "Tom", "Smith");
Methods toString by pers1 call:
alert ( "The full name of the person are:" +
pers1.toString ());
In JS, prototype is an object with method slots can be produced by JS method or property inherited slots.
Factory-based classes
JS objects Person is defined in the method, it contains a special way to call Create predefined Object.Create method to create an object of type Person;
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 JS objects Person is actually represented by factory-based classes. Examples of factory-based classes is by calling the Create method of its own:
var pers1 = Person.create ({firstName: "Tom", lastName: "Smith"});
getFullName method is invoked by pers1, as follows:
alert ( "The full name of the person are:" + pers1.getFullName ());
Each property is declared using Object.Create declaration, which contains three parameters and values, 'descriptors'writable: true and enumerable: true; as in the fifth row above. |
|
|
|