Create a custom object in Javascript

Source: Internet
Author: User
Object-oriented language requires three basic features: inheritance, polymorphism, and encapsulation and aggregation ). Like java and C ++, ecmascript is considered object-oriented because it supports these features at the same time. VaR OBJ =   New Object ();

This statement creates an object. When the constructor does not have any parameters, the brackets that follow them can be omitted. We usually operate on objects through object references. when an object is null, ecmascript starts garbage collection.ProgramDelete the object and release the memory. When an object has multiple references, you need to set all references to null to release the space occupied by the object.

1. Early and dynamic binding

Early binding means that the attributes and methods of the object have been defined before the object is instantiated, so that the compiler or interpreter can compile the machine code in advance. Java and VB support this feature, but ecmascript is not a strong type and does not support early binding.

Dynamic binding means that the compiler or interpreter knows the specific type of the object at runtime. It does not check before and only determines whether these attributes and methods are supported by the object. Ecmascript dynamically binds all variables.

2 object type

2.1 original object

The ECMA-262 defines any object that is supported by ecmascript that is not affected by the host environment as the original object, in short, the original object is the reference type defined by the ECMA-262, objects, functions, String, Boolean, number, array, and date are commonly used.

Array

Array has many common methods, many of which are similar to Java and are not described here. It should be noted that, using the push () and POP () methods, we can regard array as a stack and follow the following rules (LIFO ). Using the shift () and push () methods, the array object can be considered as a queue and follows the rules (lilo) after the arrival ). The splice () method is very useful. It easily implements some basic functions of the linked list, such as deleting data items, inserting data, and replacing data.

Date

The date class in ecmascript is based on the java. util. Date class in earlier Java versions. It can accurately represent any time of January 1, 1970 years before and after January 1, 285616 (Greenwich Mean Time. Date is a few classes that override the tostring () and valueof () methods, and the two methods are not the same. Valueof () usually indicates the time accurate to milliseconds. tostring () usually returns a personalized time representation method. For example, the same time may have different effects in different browsers.

2.2 build-in object

In addition to the basic features of the original object, the build-in object can be used when the ecmascript program starts running. Therefore, any build-in object is the original object. Currently, the ECMA-262 only defines two build-in objects: Global and math.

Global

In ecmascript, no function can exist independently. All functions must be methods of an object. For example, isnan (), isfinite (), parseint (), parsefloat (), encodeuri (), encodeuricomponent (), decodeuri (), and decodeuricomponent () are global object methods, in addition, the global object includes some attributes.

Math

Math has many attributes and methods that can be used for mathematical computation, which is similar to Java.

2.3 Host Object

Except the original object and build-in object, other objects are host objects. All BOM and DOM objects are considered as host objects.

Access methods for Class 3 members

In object-oriented programming, common class member access methods include public, protected, and private. In ecmascript, there is only one access mode, and all the attributes and methods of the object are visible. Therefore, you need to pay extra attention to system security issues during program design. Before there is a reasonable program specification, programmers compile ecmascriptCodeUsually, a standard naming method is used to indicate that the attribute or method is private (only description, actually public), for example, adding an underscore before and after the name, or only underline the name. In addition, there is no static method in ecmascript.

4 This keyword

This keyword is a very important concept in ecmascript and is usually used in object methods.

Function Whatfruit () {
Alert (This. Color );
}

VaR Table1 =   New Object;
Table1.fruit =   " Apple " ;
Table1.whatfruit = Whatfruit;
VaR Table 2 =   New Object;
Table2.fruit =   " Pear " ;
Table2.whatfruit = Whatfruit;
Table1.whatfruit (); // Output Apple
Table2.whatfruit (); // Output Pear


When no object or this is referenced before a variable, ecmascript considers the variable as a local or global variable, and searches for the variable locally and globally, if not found at the end, null is output in alert.

5. Custom classes and objects

5.1 factory Method

Create a factory method in ecmascript and return a specific type of object, so as to implement concise and applicable code.

Function Createfruit () {
VaR Tempfruit =   New Object;
Tempfruit. Name =   " Apple " ;
Tempfruit. Number =   5 ;
Tempfruit. showname =   Function () {
Alert (This. Name );
} ;
Return Tempfruit;
}

VaR Fruit1 = Creatfruit ();
VaR Fruit2 = Creatfruit ();


You can add a parameter to createfruit () to input the parameter value. With ecmascript being normalized, this method of object creation is no longer popular, partly because of syntax and partly because of functionality, for example, each object instance has its own showname method, which brings some overhead to memory management.

5.2 Constructor

Select a class name. The first letter is in upper case. The class name is the name of the constructor. Creating a constructor is similar to a factory method. The difference is that you need to use the new keyword to create an object reference. Using constructors to create objects has the same drawbacks as using the factory method.

Function Fruit (name, number) {
This . Name = Name;
This . Number = Number;
This . Showname =   Function () {
Alert (This. Name );
} ;
}

VaR Fruit1 =   New Fruit ( " Apple " , 5 );
VaR Fruit2 =   New Fruit ( " Pear " , 3 );


5.3 use prototype

You can use the prototype attribute to create a new object. First, an empty constructor is required to create a class name, and all attributes and methods are directly allocated to the prototype attribute.

Function Fruit () {
}
Fruit. Prototype. Name =   " Apple " ;
Fruit. Prototype. Number =   5 ;
Fruit. Prototype. showname =   Function () {
Alert (This. Name );
} ;

VaR Fruit1 =   New Fruit ();
VaR Fruit2 =   New Fruit ();


However, this also has some shortcomings. First, there are no parameters in the constructor, causing some trouble in Initialization. Second, when an attribute points to an object rather than a method, the object will be shared by all instances, any changes will affect the use of other object references.

5.4 mixed use of factory methods and prototype

This concept is simple: Use the constructor to define all attributes except methods, and use prototype to define object methods. In this way, each method is created only once, and each object can have its own object instance attributes.

Function Fruit (name, number) {
This . Name = Name;
This . Number = Number;
This . Owner =   New Array ( " Jerry " , " Terry " );
}
Fruit. Prototype. showname =   Function () {
Alert (This. Name );
} ;

VaR Fruit1 =   New Fruit ( " Apple " , 5 );
VaR Fruit2 =   New Fruit ( " Pear " , 3 );


5.5 Dynamic Prototype

Simply put, this method uses an identifier to determine whether prototype has been directed to a method, so as to ensure that these methods are created and directed only once.

5.6 hybrid factory Method

This method is the same as the classic factory method and constructor method in the object Method Memory Management. It is generally not recommended to use this method, except for some special cases (this is an example in XML in Javascript ).

6. Modify an object

You can use the prototype object to modify the object. In addition to custom objects, the original ecmascript object also has the prototype attribute. You can directly use prototype to create a new method for the object.

Number. Prototype. tohexstring =   Function () {
Return This. Tostring (16);
} ;
VaR Inum =   10 ;
Alert (inum. tohexstring ()); // Output


In addition, you can use prototype to easily modify existing methods and point the method name to the new method. Note that, after pointing to a new method, the original method will not be used by any object and will be destroyed by the garbage collector, so that the original method will no longer exist. A safer solution is to create a new reference to save the original method, and then overwrite the original method.

Specifically, you can create an object in ecmascript. After an object reference is created, you can add a new method to the object and use it immediately in the object reference. This is a feature of ecmascript, but it is not recommended to avoid unnecessary troubles, such as reading comprehension and documentation.

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.