Object-oriented programming for JavaScript BASIC programming

Source: Internet
Author: User

JavaScript is an interpreted language, and there is no obvious difference between compile-time and run-time, so a more dynamic approach is needed. JavaScript does not have a formal class concept, and we can use it to create new object types at run time, and we can change the properties of existing objects at any time.

JavaScript is a prototype-based object-oriented language, in which each object has a prototype that inherits properties and methods from the prototype. When accessing an object's properties or invoking the object's methods, the interpreter first checks to see if the object has an instance property or method with the same name. If so, the instance property or method is used, and if not, the interpreter checks to see if there are appropriate properties or methods in the object's prototype. In such a special environment, the public methods and properties of all objects of the type (class) can be encapsulated in the prototype, and each object can have instance properties that represent the specific data for that object.

In JavaScript, the prototype relationship is recursive. That is, the prototype of an object is also an object, and the prototype itself may have a prototype. This means that if the property being accessed is not an instance property of the object, nor is it a property of the object's prototype, the interpreter will search the prototype chain along the prototype. If you haven't found it yet, continue searching up the prototype chain. The object in JavaScript is the superclass of all objects, so object is the end point of the search. If it is not found in object, then the value returned is undefined. If the method is called, the error is thrown.

First, JavaScript object-oriented basis

1. Creation of objects

Objects in JavaScript are created using a new operator and a constructor. A constructor is a special type of function that prepares the use of a new object by initializing the memory that the object occupies. We can use a constructor with no parameters, or you can use a constructor with parameters to create the object. Such as:

var New String (); var New String (' Shanghai ');

2. Object destruction and garbage collection

Objects and other variables need to use memory, and memory resources are limited in a computer. To prevent potential memory shortages, some programming languages force programmers to carefully manage the use of memory in their programs. Fortunately, JavaScript does not require programmers to manage memory. When JavaScript creates an object, the interpreter automatically allocates memory to the object. When the object is finished, the interpreter automatically cleans up the memory used by the object, which is garbage collection.

However, if our object code contains a large amount of data manipulation, it is best to replace the unwanted data with NULL to free up resources as soon as possible.

var New Book (); .....
After a lot of data manipulation ...
null;

If you have multiple references to the same data, you must make sure that all references are set to NULL. Otherwise, the interpreter retains the data in case it is needed again.
3. Adding object Properties dynamically

var New Object (' Hello World '); alert (obj.name); // undefinedobj.name= ' Jiajia '; alert (obj.name); // Jiajia

Dynamically added properties, which we call instance properties, are called instance properties because they appear only in the particular object or instance to which they are added. In contrast to this, there is a public property, such as the length property of string, which all string objects have this public property. Instance properties are useful for supplementing or extending an existing object for some special purpose.

4. Dynamically Delete Object properties

var New String (' Hello World 'true; Delete Mystring.istrue;alert (mystring.istrue); // undefined;

Java programmers note that in JavaScript, delete differs from Java in that it simply removes the attribute from the object or removes the element from the array, but we cannot delete the object itself.

5. How to add objects dynamically

Like adding properties, methods can be added dynamically:

var New String (' Hello World '); function Alertsay () {alert (' no ');}; Mystring.sayno=alertsay;mystring.sayno (); // not

The above is the addition of a real-name function, we can also add an anonymous function:

var New String (' Hello World '); Mystring.sayno=function() {alert (' no ');}; Mystring.sayno (); // not

6. Object statements

If you want to use multiple properties and methods of an object in your program, you might consider using the With statement to include the object whose properties and methods you want to use with the WITH statement syntax:

 with (object) {    ... Statement ...}

For example:

 with (document.myform) {     if(username.value== ')if(password.value== ')      )}

A For statement is a special looping statement that iterates through all the properties of an object. Note is all properties!
For example, the following example iterates through all the properties of the document object with the For...in statement and displays it:

document.write (All properties of the ' );  for (var in document) {    document.write (i+ ' <br/> ');}

Ii. creating custom JavaScript classes and objects

1. Factory mode

The so-called factory approach is to create objects first and then add properties and methods to the objects.

Serial Production with Ginseng:

functionCreateperson (name) {varPersonobj =NewObject (); Personobj.name=name; Personobj.say=function() {alert (' Who's ' + This. Name); }     returnPersonobj;} varPersion1 = Createperson (' Fanfan ')); varPersion2 = Createperson (' Xiaoxiao ')); Person1.say ();//FanfanPerson2.say ();//Xiaoxiao

As JavaScript is normal, this way of creating objects is not advocated. There are two reasons:

(1) Semantically, that is, this method does not apply to the creation of an object by the new operator;

(2) Functionally, each time the Createperson () function is called, a new function say () is built. This means that each object has its own version of the Say () method. Then in reality, each object is sharing the same method.

2. How to construct a function

Similar to Factory mode, the first letter of a class name is uppercase.

function Person (name) {    this. Name = name;       This function () {      alert (' who is ' +name);}    } var New Person (' Fanfan '); var New Person (' Xiaoxiao ');

As we can see, there is no object created inside the constructor, but the This keyword is used instead. When the constructor is called with the new operator, an object is created before the first row of the constructor is executed, which can be accessed through the this operator. We can then assign a property directly to this, which is returned by default as a function value.

Then, as with Factory mode, a constructor is created without creating an object, and a new function is generated.

3. Prototype mode

The prototype method takes advantage of the object's prototype property. In the object class, each object has a prototype property that represents the parent class of the object.

function Person () {}person.prototype.name= ' Fanfan '; Person.prototype.say=function() {alert (' Who's ' +this. name);} var New Person (); var New Person ();

When new person () is called, all prototype properties and methods are immediately assigned to the created object, so that all the person instances contain pointers to the same say () function. Semantically, properties and methods belong to an object, which solves the problem of repeating the generated function earlier. In addition, in this way, we can also use the instanceof operator to detect the object type that a given variable points to.

instanceof person); // true

However, the prototype method cannot initialize the property value by passing a parameter through the constructor.
4. Mixed constructors and prototypes

Use constructors to define the properties of an object, using a prototype method to define the object. This way, the function is created only once, and each object has its own instance of the object property.

function Person (name) {     this.name=name;} Person.prototype.say=function() {         alert (' Who's ' +thisvar New Person (' Fanfan 'varnew person (' Xiaoxiao '); alert (Person1.say ()); // fanfan alert (Person1.say ()); // Xiaoxiao

5. Dynamic Prototyping Mode

functionPerson (name) { This. name=name; if(typeofPerson.initial = = ' undefined ') {Person.prototype.say=function() {alert (' Who's ' + This. Name); } person.initial=true; }      } varPerson1 =NewPerson (' Fanfan '); varPersion2 =NewPerson (' Xiaoxiao '); Alert (Person1.say ());//FanfanAlert (Person1.say ());//Xiaoxiao

6. Create objects using JSON format

var personobj={    firstname:' Fanfan ',    LastName:' Xiaoxiao ', age    :50 ,    tellyourage:function{           alert (' yourage: ' +this. Age)    }}

There is no essential difference from the factory approach, just faster.
Third, the realization of object inheritance

Creating subclasses inherits all the properties and methods of the superclass, including the implementation of constructors and methods. Remember that all properties and methods are common, so subclasses can access these methods directly. Subclasses can also add new properties and methods that are not in the superclass, or override properties and methods in the superclass.

1. Object posing

The so-called object posing, is the new class impersonating the old class (the old class must take the form of constructors), so as to achieve the purpose of inheritance, the principle is as follows: The constructor uses the This keyword to assign values to all properties and methods (that is, the constructor method with class declaration). Because the constructor is just a function, you can make the ClassA constructor a ClassB method, and then call it. CLASSB will receive the properties and methods defined in the ClassA constructor.

function Person (name) {      this. name=name;       this. say=function() {             alert (' Who's ' +this. name);         }         }

We know that the keyword this refers to the object that the constructor is currently creating. In the method, this points to the owning object. This principle is to use people as a regular function to establish the inheritance mechanism, rather than as a constructor function.

 function   Whitepeople (name) { this . inherit=people; //      impersonating  this . Inherit (name); //      inherit  delete  this . Inherit; //      delete inheritance  this . Area = function   () {alert ( ' I'm in Europe '  var  tom=new  whitepeople (' Tom ' ); Tom.say (); Tom.area ();  

Therefore, the new attribute and the new method must be defined after the inheritance is removed, in order to avoid overwriting the related properties and methods of the parent class.

Object impersonation can support multiple inheritance, which means that a class can inherit multiple superclass.

functionPerson (name) { This. name=name;  This. say=function() {alert (' Who's ' + This. Name); }         }functionWorker (pay,work) { This. pay=Pay ;  This. work=Work ;}functionCity_worker (name,pay,work) { This. Inherit =people;  This. Inherit (name); Delete  This. Inherit;  This. Inherit =Work ;  This. Inherit (pay,work); Delete  This. Inherit;}varjerry=NewCity_worker (' Jerry ', ' 10000 ', ' coder '); Jerry.say (); alert (jerry.work) ;
View Code

2. Call mode

Base class. Call (object, parameter list)

function whitepeople (name) {     //this.inherit=people;//impersonate     //This.inherit ( name); /     /Inherit//Delete this.inherit;//Delete the inherited         People.call (this. Name );       This function () {        alert (' I am in Europe ')     ; var tom=New whitepeople (' Tom '); Tom.say (); Tom.area () ;

3. Apply

Apply () is also an object posing as a wrapper function. The Apply () method has two parameters, the object used for this and an array of arguments to pass to the function. The format is:

Base class. Apply (object, parameter array);

function City_worker (name,pay,work) {  people.apply (this,new  Array (name));  Worker.apply (this, [pay,work]);} var jerry=New city_worker (' Jerry ', ' 10000 ', ' coder '); Jerry.say (); alert (jerry.work) ;

4. Prototype chain

The above three methods are inherited by the constructor, corresponding, also has the prototype function way inheritance, the prototype chain.

function Blue_collor () {}blue_collor.prototype.name= ' Jean '; Blue_collor.prototype.say=function() {    alert (' Who's ' +this. name);} function  New  blue_collor (); var New City_blue_collor (); J1.say ();

Note When you use a prototype chain inheritance, you cannot have any parameters within the base class constructor.

Object-oriented programming for JavaScript BASIC programming

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.