JavaScript Learning-Improving textual _javascript skills

Source: Internet
Author: User
Tags inheritance instance method square root

JavaScript Learning-Improving articles

A. An object in JavaScript.

The object in JavaScript is a collection of key-value of a set of data, somewhat similar to the HashMap in Java, all of which are property in object. In general, creating an object in JavaScript is accomplished with "new" plus the constructor function. such as New Date (), New Object (), and so on.

var book = new Object ();
Book.name = "JavaScript is cool";
Book.author = "Tom";
Book.pages = 514;

The name and page in the example above are the property in the object named book. We can use Delete to delete the property in object: "Delete book.name;" In addition to objects such as object, date, and Buildin, we can write our own constructor function and then use new to create our own objects. As the book above can be written:

function book (name, author, page) {
THIS.name = name;
This.author = author;
this.page = page;
}
var abook = new book ("JavaScript are Cool", "Tom", 514);

two. Use of function

In JavaScript, a function is a data type, and all function is an object derived from the Buildin function object. So function in JavaScript can be passed as a parameter, either as the property of object or as a function to return a value. A function is used in JavaScript in two ways, one as a constructor, preceded by a new keyword to create an object. One is called as method, for other objects.

Note that function and method are equivalent in Chinese and can be generalized in some languages. But in JavaScript, they are different. The function itself is an object, and when he belongs to an object as a method, it becomes an object's approach, which is equivalent to the attribute of an object species. This means that the method is relative to an object, and the function in some cases 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 example above, function Book_getreader () becomes a method named Getreader in book. Call () and apply () are two methods of function object, which can also be invoked using a function as the method of another object. Call () and apply () all require parameters, and the first parameter is the calling object, which is the object that this refers to when this occurs inside a function. The difference between call () and apply () is that calls () can pass arbitrary length parameters, and the object is invoked whenever the first argument is used. Instead, apply accepts only two parameters, and you need to put all parameters except the calling object into an array. That

function Getbookswithsameauthor (form, to) {
var name = This.author;
var books = ...
Get books written by name and from year ' to '
return to books;
}

var abook = new book ("JavaScript are Cool", "Tom", 514);
var books = Getbookswithsameauthor.call (Abook, 1990, 2005);
Or
var books = getbookswithsameauthor.apply (Abook, [1990, 2005]);

When a function does not act as a method of an object, JavaScript considers it to be a method of a Globle object, which is the window class in the Globle object in browser. So from this perspective, function and method can be unified again.

Function object also has a very important property:prototype. It is a predefined prototype object. When a function is used as an object's constructor, the Protptype property will play a role, and the Chinese translation is called a prototype. The new object of JavaScript is created by the prototype of the function. We can also use prototype to dynamically add attributes to an object, such as:

function book (name, author, page) {
THIS.name = name;
This.author = author;
this.page = page;
}
var abook = new book ("JavaScript are Cool", "Tom", 514);

Book.prototype.getInfo = GetInfo;
function GetInfo () {
return THIS.name + "written by" + This.author + "with" + This.page + "pages";
}

Alert (Abook.getinfo ());

Here is an example of using the prototype method to implement callback:

Function.prototype.andthen=function (g) {
var f=this;
return function () {
f (); G ();
}
};

function Manager () {
This.callback=function () {}; Doing nothing
This.registercallback=function (callbackfunction) {
this.callback= (This.callback). Andthen (callbackfunction);
}
}

VAR manager=new manager ();
Manager.registercallback (Sayhi);
Manager.registercallback (Saybye);
Manager.callback ();

Three. oo in JavaScript
An object in JavaScript is a collection of properties and methods. JavaScript also has concepts that correspond to Java class and instance. We can define the JavaScript

A function (a subclass of a function Class) is considered class, and the object constructed using this function is instance. Corresponds to the Java Instance property, Instance

method, Class (Static), class, and JavaScript can all be implemented.
1. Instance Property
The Instance property is the property defined in the Cuntructor function, and for each Instance there will be a copy.
2. Class Property
The Class property is actually the Cunstructor function as the object itself (unlike Java, method is not data, not objects).
3. Instance method
Instance method is the method that belongs to an object, in which this represents the object that is subordinate to it, noting that although it is Instance methods, not every Instance has a copy of this approach. All instance share a method.
4. Class method
Class method can also be understood as the constructor function as the object itself, and the object created by this constructor is not directly related. So using this in the class method will create confusion. Because this does not refer to the object of the desired action, but to a function object (constructor).

The following example defines a complex number of objects that contain the above four fields and are worth looking at carefully:
/*

* Complex.js:

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

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

* Imaginary number and that the imaginary number I are the

* Square root of-1.

*/

/*

* The defining a class is defining the constructor

* Function of the class. This is constructor should initialize any

* Instance properties of the object. These are the essential

* "state variables" which 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 into 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 would

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

* Methods operate implicitly on the This keyword. For many methods,

* No other arguments are needed.

*/

Return the magnitude of a complex number. This is defined

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

Complex.prototype.magnitude = function () {

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

};

Return a complex number "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 the object is used as a string.

Complex.prototype.toString = function () {

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

};

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

is invoked when a Complex the object is treated as a primitive value.

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

/*

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

* constants, and any needed class properties as properties of the

* constructor function itself (instead of as properties of the

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

* Don't 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 as

"Constants." (note, though, this they are not actually read-only.)

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

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

complex.i = new Complex (0,1);

four. Inheritance of objects

JavaScript simulates inheritance in a variety of 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);
}

You can simulate the inheritance from superclass by first defining the subclass Inheritfrom method, calling this method (the method name is not important), or using the call method of function Object directly to make this argument. Note the this point when calling superclass. This method performs the Cunstructor function of Supperclass first when executing the subclass Cunstructor function. The disadvantage of this method is that subclasses are only in their own constructors, Invokes this as a parameter to the constructor of the parent class, giving the constructor a subclass of all the fields of the parent class. Therefore, any parent class that is defined outside the constructor (through prototype) cannot inherit. Also, the constructor of a subclass must call the constructor of the parent class before defining its own domain, lest the subclass's definition be overwritten by the parent class. Using this method subclass also tries not to use prototype to define a subclass's domain, because the definition of prototype executes after the subclass new, so it must be in danger of being overwritten by the definition of the parent class before invoking the parent class constructor.


2. Using prototype:

Function Superclass () {
This.bye = Superbye;
This.hello = Superhello;
}

function Subclass () {
This.bye = Subbye;
}
Subclass.prototype = new superclass ();
SubClass.prototype.constructor = superclass;

Here, a superclass instance is set to the subclass prototype: Protytype, since the new superclass instance will certainly invoke all the domains defined by the parent class prototype, this method avoids a problem with the previous method. The parent class can describe the domain by prototype. You can implement inheritance from superclass. This method also has drawbacks, because the subclass of the Peototype is already an instance of the parent class (object instance), can no longer be instantiated, so when the new subclass instance, all the superclass data types of the parent class (see JavaScript data type) will be reference Copy rather than data copy. Simply put, all the parent class fields exist in subclasses, but look like static fields in Java share between subclasses. Being changed by a subclass, all subclasses will change.

Notice the last sentence here, changing the constructor attribute in the subclass prototype. It has no effect on the use of subclasses, only to make the subclass instance return subclass when the Instanceof method is invoked.

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 calling instanceof, the subclass returns the parent class name, the benefit of which is to liberate the parent class on the basis of the constructor inheritance, and the parent class can define its own domain using prototype, but subclasses still do not recommend using prototype. To avoid being overwritten by the parent class. In order to return the instanceof of the subclass to the correct type, we can refine it again:

function Subclass () {
This.base = new Supperclass ();
for (var key in This.base) {
if (!this[key]) {
This[key] = This.base[key];
}
}

This.saybye = Subbye;
}

Copies all the parent class fields to a subclass, no longer returns the parent class, and the correct type can be returned when the subclass instance is instanceof.

Five. Use of this

Typically, this represents the previous mentioned Globle object, which is the window object in the browser environment. When a function acts as a method of an object, this represents the object to which this function belongs. The following code has a lattice error that relates to the use of this:

function Employee (a) {
THIS.name = A;
}

function init () {
John = Employee ("Johnson");
alert (john.name);
}

We are missing a new keyword in init (). The code then complains because browser the employee as a method of window obect, where this refers to Window object. Init () should read:

function init () {
John = new Employee ("Johnson");
alert (john.name);
}

We can also modify the employee's constructor function to prevent similar errors:

function Employee (a) {
if (!) ( This is instanceof employee) return to new employee (a);
THIS.name = A;
}

In this way, even if we use the original init () method, there is no error.

Six. Array in JavaScript
Array and object are essentially the same, except that the array needs to index its properties. An integer with index >=0.
Array has a series of Buildin methods:
1. Jion () connects all the element in the array in string form:
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 the array's element CIS
var a = [1,2,3];
A.reverse ();
s = A.join (); //s = "3,2,1"

3. Sort () sorting, by default alphabetical order case sensitive, you can customize the sorting method.

var a = [111,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 () to connect multiple array
  var a = [1,2,3];
  A.concat (4,5);          //return [ 1,2,3,4,5]
  A.CONCAT ([4,5]);        / return [1,2,3,4,5]
  A.CONCAT ([4,5], [6,7])   //return [1,2,3,4,5,6,7]  
  A.concat (4,[5,[6,7]]);  //return [1,2,3,4,5,6,7]

5. Slice () returns the slice of array, the original array is 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 represents the position, the second parameter represents the deletion length, and any subsequent long arguments represent the elements added at the 1 deletion location.
var a = [1,2,3,4,5,6,7,8];
A.splice (4); //Returns [5,6,7,8]; A is [1,2,3,4]
A.splice (1,2); //Returns [2,3]; A is [1,4]
A.splice (1,1); //Returns [4]; A is [1]

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

7. Push () and pop () add or remove an element to the end of the array
8. Unshift () and shift () adds or deletes an element to the beginning of the 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.