JavaScript learning-improve article _ javascript skills

Source: Internet
Author: User
JavaScript learning-improve

1. Objects in JavaScript.

Objects in JavaScript are a collection of key-values of a set of data, which is somewhat similar to HashMap in Java. All the data is the property of the Object. generally, an object created in JavaScript is implemented using "new" and constructor function. such as new Date () and new Object.

Var book = new Object ();
Book. name = "JavaScript is Cool ";
Book. author = "tom ";
Book. pages = 514;

In the above example, name and page are the property in the object named book. we can use delete to delete the property in the Object: "delete book. name ;". in addition to buildin objects such as objects and dates, we can write our own constructor functions, and then use new to create our own objects. the above book can be written:

Function Book (name, author, page ){
This. name = name;
This. author = author;
This. page = page;
}
Var every k = new Book ("JavaScript is Cool", "tom", 514 );

Ii. function usage

In JavaScript, function is a data type, and all functions are derived from the function object of buildin. therefore, in JavaScript, a function can be passed as a parameter, an Object's property, or a function's return value. function can be used in JavaScript in two ways. One is as a constructor, followed by a new keyword to create an object. one method is called for other objects.

Note that function and method have the same meaning in Chinese and can be used in some languages. however, they are different in JavaScript. function itself is an object, and when treated as a method, it belongs to an object, it becomes a method of this object, which is equivalent to an object property. that is to say, the method is relative to an object. In some cases, the function becomes the method of an object.

Function Book (name, author, page ){
This. name = name;
This. author = author;
This. page = page;
This. getReader = Book_getReader;
}

Function Book_getReader (){
//....
}

In the preceding example, function Book_getReader () becomes a method named getReader in the Book. call () and apply () are two methods of Function object. They can also use one function as the method of another object. both call () and apply () require parameters, and the first parameter is the call object, that is, the object referred to by this when this occurs inside the function. the difference between call () and apply () is that call () can pass any length parameter, as long as the first parameter calls the object. apply only accepts two parameters. You need to put all parameters except the called object into an array. that is:

Function getBooksWithSameAuthor (form, ){
Var name = this. author;
Var books =...
// Get books written by name and from year "from" to year ""
Return books;
}

Var every k = new Book ("JavaScript is Cool", "tom", 514 );
Var books = getBooksWithSameAuthor. call (limit k, 1990,200 5 );
Or
Var books = getBooksWithSameAuthor. apply (abook, [1990,200 5]);

When a function does not act as the method of an Object, JavaScript considers it to belong to the method of a Globle Object. This Globle Object is a window class in Browser. from this perspective, functions and methods can be unified.

Function object also has a very important property: prototype. it is a predefined prototype object. when a Function is used as the constructor of an object, the protptype property will play a role. A Chinese translation is called a prototype. the new JavaScript Object is created through the function prototype. at the same time, we can also use prototype to dynamically add attributes to objects, such:

Function Book (name, author, page ){
This. name = name;
This. author = author;
This. page = page;
}
Var every k = new Book ("JavaScript is Cool", "tom", 514 );

Book. prototype. getInfo = getInfo;
Function getInfo (){
Return this. name + "written by" + this. author + "with" + this. page + "pages ";
}

Alert (cmdk. getInfo ());

The following example uses the prototype method to implement callback:

Function. prototype. andThen = function (g ){
Var f = this;
Return function (){
F (); g ();
}
};

Function Manager (){
This. callback = function () {}; // do nothing
This. registerCallback = function (callbackFunction ){
This. callback = (this. callback). andThen (callbackFunction );
}
}

Var manager = new Manager ();
Manager. registerCallback (sayHi );
Manager. registerCallback (sayBye );
Manager. callback ();

Iii. OO in JavaScript
Objects in JavaScript are a collection of attributes and Methods. JavaScript also corresponds to the Java Class and Instance concepts. we can define

Function (subclass of the Function Class) is considered as a Class, and the object constructed using this function is Instance. corresponding to the Java Instance Property, Instance

Method, Class (static) property, Class Method, and JavaScript can all be implemented.
1. Instance Property
The Instance Property is the property defined in the cuntructor function, and each instance has a copy.
2. Class property
Class Property is actually the Property of the cunstructor function as the object itself (unlike Java, in Java, method is not data, not an object ).
3. Instance Method
Instance Method refers to the method of an object. this In the method represents the object that this Method belongs to. Although it is an Instance Method, not every Instance has a copy of this method, all instances share a method.
4. Class Method
The Class Method can also be understood as the constructor function as the Method of the object itself, and there is no direct connection with the object created by the constructor. therefore, using this in the Class Method produces confusion. this is because this refers to a Function Object (constructor) instead of an Object to be operated ).

The following example defines a complex object that contains the above four fields. It is worth looking:
/*

* Complex. js:

* This file defines a Complex class to represent complex numbers.

* Recall that a complex number is the sum of a real number and

* Imaginary number and that the imaginary number I is

* Square root of-1.

*/

/*

* The first step in defining a class is defining the constructor

* Function of the class. This constructor shoshould initialize any

* Instance properties of the object. These are the essential

* "State variables" that make each instance of the class different.

*/

Function Complex (real, imaginary ){

This. x = real; // The real part of the number

This. y = imaginary; // The imaginary part of the number

}

/*

* The second step in defining a class is defining its instance

* Methods (and possibly other properties) in the prototype object

* Of the constructor. Any properties defined in this object will

* Be inherited by all instances of the class. Note that instance

* Methods operate implicitly on the this keyword. For each methods,

* No other arguments are needed.

*/

// Return the magnqueue of a complex number. This is defined

// As its distance from the origin (0, 0) of the complex plane.

Complex. prototype. magntasks = function (){

Return Math. sqrt (this. x * this. x + this. y * this. y );

};

// Return a complex number that is the negative of this one.

Complex. prototype. negative = function (){

Return new Complex (-this. x,-this. y );

};

// Convert a Complex object to a string in a useful way.

// This is invoked when a Complex object is used as a string.

Complex. prototype. toString = function (){

Return "{" + this. x + "," + this. y + "}";

};

// Return the real portion of a complex number. This function

// Is invoked when a Complex object is treated as a primitive value.

Complex. prototype. valueOf = function () {return this. x ;}

/*

* The third step in defining a class is to define class methods,

* Constants, and any needed class properties as properties of

* Constructor function itself (instead of as properties of

* Prototype object of the constructor). Note that class methods

* Do not use the this keyword: they operate only on their arguments.

*/

// Add two complex numbers and return the result.

Complex. add = function (a, B ){

Return new Complex (a. x + B. x, a. y + B. y );

};

// Subtract one complex number from another.

Complex. subtract = function (a, B ){

Return new Complex (a. x-B. x, a. y-B. y );

};

// Multiply two complex numbers and return the product.

Complex. multiply = function (a, B ){

Return new Complex (a. x * B. x-a. y * B. y,

A. x * B. y + a. y * B. x );

};

// Here are some useful predefined complex numbers.

// They are defined as class properties, where they can be used

// "Constants." (Note, though, that they are not actually read-only .)

Complex. zero = new Complex (0, 0 );

Complex. one = new Complex (1, 0 );

Complex. I = new Complex (0, 1 );

Iv. Object Inheritance

JavaScript can simulate inheritance in multiple ways.
1. Use function:

Function superClass (){
This. bye = superBye;
This. hello = superHello;
}

Function subClass (){
This. inheritFrom = superClass;
This. inheritFrom ();
This. bye = subBye;
}

Or:

Function subClass (){
SuperClass. call (this );
}

First define the subClass inheritFrom method, then call this method (the method name is not important), or directly use the call method of Function Object to make this a parameter, you can simulate the inheritance from superClass. note that this points to when calling superClass. this method is to first execute the cunstructor function of supperClass when executing the cunstructor function of subClass. the disadvantage of this method is that the subclass only calls the constructor of the parent class in its own constructor and assigns the constructor to all fields of the parent class. therefore, any fields defined by the parent class outside the constructor (through prototype) cannot be inherited by subclass. in addition, the constructor of the subclass must call the constructor of the parent class before defining its own domain, so that the definition of the subclass is overwritten by the parent class. if you use this method to subclass, try not to use prototype to define the domain of the subclass. Because prototype is executed after the new subclass, it must be before calling the parent class constructor, there is also a risk of being overwritten by the definition of the parent class.


2. Use prototype:

Function superClass (){
This. bye = superBye;
This. hello = superHello;
}

Function subClass (){
This. bye = subBye;
}
SubClass. prototype = new superClass ();
SubClass. prototype. constructor = superClass;

Set a superClass instance to the prototype of subclass: protytype. Because the new superClass instance will certainly call all the fields defined by the parent prototype, therefore, this method avoids a problem with the previous method. The parent class can use prototype to describe the domain. can be inherited from superClass. this method also has its disadvantages. Because the peototype of the subclass is already an instance of the parent class (Object instance) and cannot be instantiated, when the new subclass instance is used, all non-basic data types of the parent class (see JavaScript data types) will be reference copy rather than data copy. in short, all the parent class fields exist in the subclass, but it looks like the static field in Java to share them between the subclass. changed by a subclass. All subclasses will change.

Note that the last sentence here changes the constructor attribute in prototype of the subClass. It does not affect the usage of the subClass, just to make the subClass instance return subClass when the instanceOf method is called.

3. Parasitic Inheritance (Parasitic Inheritance)
Function superClass (){
This. bye = superBye;
This. hello = superHello;
}

Function subClass (){
This. base = new supperClass ();
Base. sayBye = subBye;
Return base;
}

This inheritance is actually an extension, because when instanceOf is called, The subclass will return the parent class name. Its advantage is that it frees the parent class from the inheritance of constructors, the parent class can use prototype to define its own domain, but prototype is not recommended for subclass to avoid overwriting by the parent class. to make the instanceof of a subclass return the correct type, we can improve the following:

Function subClass (){
This. base = new supperClass ();
For (var key in this. base ){
If (! This [key]) {
This [key] = this. base [key];
}
}

This. sayBye = subBye;
}

Copy all the parent class fields to the subclass without returning the parent class. The correct type can be returned for the instanceof subclass instance.

5. usage of this

Generally, this indicates the Globle Object mentioned above. that is, the window Object in the Browser environment. when a function acts as the method of an object, this indicates the object to which the function belongs. the following code has a grid error and involves the use of this:

Function Employee (){
This. name =;
}

Function init (){
John = Employee ("Johnson ");
Alert (John. name );
}

In init (), we have missing a new keyword. therefore, this code will report an error, because Browser regards "Employee" as a method of window obect. this indicates window object. init () should be changed:

Function init (){
John = new Employee ("Johnson ");
Alert (John. name );
}

At the same time, we can modify the constructor function of the Employee to prevent similar errors:

Function Employee (){
If (! (This instanceof Employee) return new Employee ();
This. name =;
}

In this way, even if the original init () method is used, no error is reported.

Vi. Array in JavaScript
The Array and Object are essentially the same, but the Array needs to be indexed by the index. The index is an integer greater than or equal to 0.
Array has a series of buildin methods:
1. jion () connects all elements in array in the form of string:
Var a = [1, 2, 3];
S = a. join (); // s = "1, 2, 3"
S = a. join (":"); // s = "1: 2: 3"

2. reverse () reverses the number of elements in Array.
Var a = [1, 2, 3];
A. reverse ();
S = a. join (); // s = "3, 2, 1"

3. sort by sort (). case sensitive is sorted alphabetically by default. You can customize the sorting method.

Var a = [113,4, 33,2];
A. sort (); // a = [111,2, 33,4]

A. sort (function (a, B) {// a = [2, 4, 33,111]
Return a-B; // Returns <0, 0, or> 0
});

4. concat () connects multiple arrays
Var a = [1, 2, 3];
A. concat (); // return [, 5]
A. concat ([4, 5]); // return [1, 2, 3
A. concat ([], []) // return [, 7]
A. concat (4, [5, [6, 7]); // return [1, 2, 3, 4, 5, 6, 7]

5. slice () returns the Array slice. The original Array remains unchanged.
Var a = [1, 2, 3, 4, 5];
A. slice (0, 3); // Returns [1, 2, 3]
A. slice (3); // Returns [4, 5]
A. slice (1,-1); // Returns [2, 3, 4],-1 means the last index of the array
A. slice (-3,-2); // Returns [3], from the third last index to the second last index

6. splice adds or deletes an element to an Array. The first parameter indicates the location, the second parameter indicates the deletion length, and the other parameter indicates the elements added at the 1 deletion position.
Var a = [1, 2, 3, 4, 5, 6, 7, 8];
A. splice (4); // Returns [5, 6, 7, 8]; a is [1, 2, 4]
A. splice (); // Returns []; a is []
A. splice (1, 1); // Returns [4]; a is [1]

Var a = [1, 2, 3, 4, 5];
A. splice (, 'A', 'B'); // Returns []; a is [, 'A', 'B', 5]
A. splice (, [], 3); // Returns ['A', 'B']; a is [, [],]

7. push () and pop () add or delete an element to or from the end of Array
8. unshift () and shift () add or delete an element to or from the beginning of Array

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.