Basic javascript programming objective Object-Oriented Programming

Source: Internet
Author: User

Basic javascript programming objective Object-Oriented Programming

Javascript is an interpreted language, and there is no significant difference between compilation and runtime. Therefore, a more dynamic method is required. Javascript does not have a formal class concept. We can use a new object type at runtime to replace it, and can change the attributes of an existing object at any time.

Javascript is a prototype-based object-oriented language. Each object has a prototype that inherits attributes and methods from the prototype. When you access the attributes of an object or call the method of an object, the interpreter first checks whether the object has an instance attribute or method of the same name. If yes, the instance attributes or methods are used. If no, the interpreter checks whether the object's prototype has the appropriate attributes or methods. In such a special environment, all the object public methods and attributes of this type (class) can be encapsulated in the prototype, and each object can have instance attributes that represent the specific data of this object.

In javascript, prototype relationships are recursive. That is, the prototype of an object is also an object, and the prototype itself may have another prototype. This means that if the accessed attribute is not the instance attribute of the object or the prototype attribute of the object, the interpreter will chain the prototype to the prototype. If it is not found, search for the prototype chain. In javascript, an object is the superclass of all objects, so an object is the end point of its search. If the object is not found, the returned value is undefined. If the method is being called, an error is thrown.

I. javascript object-oriented Basics

1. Object Creation

Objects in javascript are created using a new operator and a constructor. A constructor is a special type of function. It initializes the memory occupied by an object to prepare the use of a new object. We can use a constructor without parameters or a constructor with parameters to create objects. For example:

Var city = new String (); var city = new String ('shanghai ');
2. Object destruction and garbage collection

Objects and other variables require memory usage, while memory resources in a computer are limited. To prevent potential memory insufficiency, some programming languages require programmers to carefully manage the memory usage 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. After the object is used up, the interpreter automatically clears the memory used by the object, that is, garbage collection.

However, if our object code contains a large amount of data operations, it is best to replace unnecessary data with null to release resources as soon as possible.

Var book = new Book ();... after a large number of data operations... book = null;
If there are multiple references to the same data, make sure that all references are set to null. Otherwise, the interpreter retains the data for future use.
3. dynamically add Object Attributes

var obj = new Object('hello world');alert(obj.name);//undefinedobj.name='jiajia';alert(obj.name);//jiajia
Dynamically added attributes are called instance attributes because they only appear in the specific objects or instances they are added. On the contrary, there is also a public attribute, such as The length attribute of string. All string objects have this public attribute. Instance attributes help to supplement or expand existing objects for some special purposes.

4. dynamically Delete Object Attributes

var mystring = new String('hello world');mystring.isTrue = true;delete mystring.isTrue;alert(mystring.isTrue);//undefined;
Java programmers note that delete in javascript is different from Java in that it is only used to delete attributes in objects or to delete elements from arrays, but we cannot delete objects themselves.

5. Dynamic object addition method

The method can also be dynamically added like adding an attribute:

Var mystring = new String ('Hello World'); function alertSay () {alert ('no ');};
mystring.sayno=alertSay;
Mystring. sayno (); // No

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

Var mystring = new String ('Hello World'); mystring. sayno = function () {alert ('no') ;}; mystring. sayno (); // No
6. Object statements

To use multiple attributes and methods of an object in a program, you can use the with statement to include the objects whose attributes and methods need to be used 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 loop statement used to traverse all attributes of an object. Note all attributes!
For example, the following example uses the for... in statement to traverse all the attributes of the document Object and display it:

Document. write ('all attributes of the document Object are as follows: '); for (var I in document) {document. write (I +'
');}
2. Create custom javascript classes and objects

1. Factory Mode

The so-called factory method is to create an object first, and then add attributes and methods to the object.

Batch Production with parameters:

function createPerson(name){     var personobj = new Object(); personobj.name=name; personobj.say=function(){     alert('who is'+this.name); } return personobj; } var persion1 = createPerson('fanfan'); var persion2 = createPerson('xiaoxiao'); person1.say();//fanfan person2.say();//xiaoxiao
As javascript becomes more formal, this method of object creation is not recommended. There are two reasons:

(1) semantic, that is, this method does not apply to the new operator to create objects;

(2) In terms of functions, each call to the createPerson () function creates a new function say (). This means that each object has its own version of the say () method. In reality, each object shares the same method.

2. constructor Method

Similar to the factory method, the first letter of the class name is in uppercase.

function Person(name){    this.name = name;    this.say = function(){      alert('who is'+name);    }}var person1 = new Person('fanfan');var person2 = new Person('xiaoxiao');
We can see that no object is created in the constructor, but this keyword is used. When a constructor is called using the new operator, an object is created before the first line of the constructor is executed. At this time, this object can be accessed through the this operator. Then, we can directly assign an attribute to this, which is returned as a function value by default.

Then, like the factory mode, the constructor method generates a new function without creating an object.

3. Prototype

Prototype uses the prototype attribute of the object. In the object class, each object has a prototype attribute, which represents the parent class of the object.

function Person(){ }
Person. prototype. name = 'fanfan ';
Person.prototype.say=function(){
Alert ('who is '+ this. name );

}
Var person1 = new Person ();
var person2 = new Person();
When new Person () is called, all prototype attributes and methods are immediately assigned to the created object, so that all Person instances contain the same say () function pointer. In terms of semantics, attributes and methods all belong to one object, which solves the problem of repeated function generation. In addition, we can use the instanceof operator to detect the object type pointed to by a given variable.

alert(person1 instanceof Person);//true
However, the prototype method cannot pass the parameter initialization attribute value through the constructor.
4. Mixed constructor and prototype

Define object attributes using constructors and define object methods using prototype. In this way, the function is created only once, and each object has its own object attribute instance.

 function Person(name){  this.name=name;  } Person.prototype.say=function(){     alert('who is'+this.name); } var person1 = new Person('fanfan'); var persion2 = new Person('xiaoxiao'); alert(person1.say());//fanfan alert(person1.say());//xiaoxiao
5. Dynamic Prototype

 function Person(name){  this.name=name; if(typeof Person.initial == 'undefined'){ Person.prototype.say=function(){         alert('who is'+this.name);         }     Person.initial = true; }  } var person1 = new Person('fanfan'); var persion2 = new Person('xiaoxiao'); alert(person1.say());//fanfan alert(person1.say());//xiaoxiao
6. Create an object in JSON format

var personobj={    firstname:'fanfan',    lastname:'xiaoxiao',    age:50,    tellyourage:function{           alert('yourage:'+this.age)    }}
There is no essential difference with the factory method, but it is faster.
Iii. Object Inheritance implementation

Creating a subclass inherits all attributes and methods of a superclass, including constructor and method implementation. Remember that all attributes and methods are public, so sub-classes can directly access these methods. Subclass can also add new attributes and methods that are not present in the superclass, or overwrite attributes and methods in the superclass.

1. Object impersonating

The so-called object impersonating is that the new class impersonates the old class (the old class must adopt the constructor method) to achieve the purpose of inheritance. The principle is as follows: constructors use the this keyword to assign values to all attributes and methods (that is, the class declaration constructor method ). Because the constructor is just a function, you can make the constructor of ClassA A ClassB method and then call it. ClassB receives the attributes and methods defined in the ClassA constructor.

 function Person(name){  this.name=name; this.say=function(){         alert('who is'+this.name);         }     }
We know that the keyword this references the object Currently created by the constructor. In the method, this points to the object to which it belongs. This principle is to use People as a regular function to establish an inheritance mechanism, rather than as a constructor.

Function WhitePeople (name) {this. inherit = People; // impersonate this. inherit (name); // inherits delete this. inherit; // delete inherited this. area = function () {alert ('I am in euro') ;}} var tom = new WhitePeople ('Tom'); tom. say (); tom. area ();
Therefore, the new attributes and new methods must be defined after the inheritance is deleted to avoid overwriting the relevant attributes and methods of the parent class.

Object impersonation supports multi-inheritance, that is, a class can inherit multiple superclasses.

function Person(name){  this.name=name; this.say=function(){         alert('who is'+this.name);         }     }function Worker(pay,work){    this.pay=pay;    this.work=work;}function City_worker(name,pay,work){    this.inherit = People;    this.inherit(name);    delete this.inherit;      this.inherit = Work;    this.inherit(pay,work);    delete this.inherit; }var jerry=new City_worker('jerry','10000','coder');jerry.say();alert(jerry.work);
2. call Method

Base class. call (object, parameter list)

Function WhitePeople (name) {// this. inherit = People; // impersonate // this. inherit (name); // inherit // delete this. inherit; // delete inherited People. call (this. name); this. area = function () {alert ('I am in euro') ;}} var tom = new WhitePeople ('Tom'); tom. say (); tom. area ();
3. apply

Apply () is also an object impersonating an encapsulation function. The apply () method has two parameters: this object and an array of parameters to be passed 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 in the form of constructor, which corresponds to the prototype function, and also has the prototype function inheritance and prototype chain.

function Blue_collor(){}Blue_collor.prototype.name='jean';Blue_collor.prototype.say=function(){    alert('who is '+this.name);}function City_blue_collor(){}City_blue_collor.prototype = new Blue_collor();var j1 = new City_blue_collor();j1.say();
Note that the base class constructor cannot have any parameters when the prototype chain is used for inheritance.













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.