Make js object-oriented

Source: Internet
Author: User

Make js object-oriented

Requirement Analysis: complex data structures are inevitable when javascript is used. When defining objects and methods cannot solve the problem, you must consider using object-oriented methods.

Difficulty: js does not support class definition. That is to say, we cannot define a class to encapsulate the desired attributes and methods. We can directly define an object without the need for constructors.

Work und: attributes and methods can be stored in objects, so you can use objects to simulate classes.

When using js, you must have used a method similar to the following to set objects:

var myObj={};myObj.key = "value";myObj.func = function(key,value){myObj.key = value;}
The above Code defines an object myObj and defines an attribute key value as value and a method function for it. Then we can perform a test:

myObj.func("key","value2");alert(myObj.key);

What is the result? Value2

We can see that we have successfully defined the attributes and methods of an object, and modified the attributes of the object through methods. however, there is a major drawback here. This object can only be "self-intoxicated". If you need to define another object and assign the same attributes and methods, you need to repeat the above steps. in object-oriented systems, the difference between classes and objects is that classes are Object Templates. You can use constructor methods to define a series of objects with the same attributes and methods. then, we make the following improvements to imitate object-oriented:

function myObj(key,value){this.key = key;this.value = value;this.func = function(key){if(this.key ==key ){return this.value;}else{return null;}}}
This method simulates a class based on the mode of the definition method. How can this method be used?

var obj = new  myObj("key","value");alert(obj.func("key"));
Let's take a look at whether it is particularly like defining a class in java, then defining the object using the constructor method, and then calling the get method to return the value;

It is worth mentioning that: myObj is equivalent to the class name, And myObj (key, value) is equivalent to the constructor, but only integrated. attributes or methods modified using this are all public type. After definition, you can access them through objects.

To define private attributes, you can use var to modify them.

This method is the most commonly used method currently.
However, if you want to use more object-oriented features, such as inheritance and polymorphism, you can define classes in a better way.

The biggest problem with using the constructor method is that you need to use new to create an object. Although this method is easy to use, it is a waste of memory. That is to say, every time you create an object, all attributes and methods will re-allocate the memory. In fact, js simulation classes are not really classes after all, and some attributes and methods can be shared, this reminds us of java Singleton mode and static variables.

Javascript stipulates that all constructors have one attribute, and prototype points to another object. All attributes and methods of this object will be inherited by the constructor, that is to say, all static attributes and methods can be defined on prototype. For example:

function myObj(key,value){this.key = key;this.value = value;this.func = function(key){if(this.key ==key ){return this.value;}else{return null;}}}myObj.prototype.type = "staticType";myObj.prototype.get = function(){}

In this way, no matter how many objects are created, their property type and method get are shared.

When using this and prototype, the structure of the Code is somewhat messy. Those who are not very skilled in js cannot understand and use the code, so how can we make improvements easier to use?

Here we recommend a simple method, that is, discard the this and prototype keywords and imitate the singleton mode to create objects.

For example, to create an Animal class:

Var Animal = {getInstance: function () {var animal = {}; animal. name = "Kate"; animal. run = function () {alert ("100 km/h") ;}; return animal ;}};


The principle is very simple. The object defines a method attribute getInstance. This method is a common Singleton mode in java and can also be understood as a factory mode. To create an object, call the constructor:

var a = Animal.getInstance();a.run();
Animal is very similar to a class. getInstance is a static method.

Object-oriented Encapsulation has been mentioned. Let's talk about inheritance.

Define another class (object ):

var Cat = {    getInstance:function(){var cat= Animal.getInstance();cat.name="kite";cat.catchMouse = function(){    alert("can do");}; return cat;    }};
Cat class has the same constructor getInstance, but when Cat creates an object, it uses Animal as the template and adds its own attributes and methods to implement inheritance. Let's test it:

var cat1 = Cat.getInstance();cat1.run();cat1.catchMouse();
It can be proved that we can indeed call run () and catchMouse (), that is, the inheritance problem is solved, so what about polymorphism? Can a subclass override the parent class method? Can a subclass attribute override the attributes of the parent class?

Continue test:

alert(cat1.name);
It can be concluded that the value of cat1.name has been replaced, and the method is of course the same. Next, we need to consider how to obtain shared attributes, just like static attributes in Java (static variables in java are class variables and do not advocate calling through objects, but can be called, all object calls are in the same State.) What should we do?

var Cat = {legNum:4,    getInstance:function(){var cat= Animal.getInstance();cat.name="kite";cat.catchMouse = function(){    alert("can do");}; cat.getLegNum = function(){cat.legNum = Cat.legNum;}cat.changeLegNum = function(legNum){Cat.legNum = legNum;}return cat;    }};



Test whether the legNum attribute is shared:

var cat1 = Cat.getInstance();var cat2 = Cat.getInstance();alert(cat1.getLegNum()==cat2.getLegNum());cat1.changeLegNum(3);alert(cat1.getLegNum()==cat2.getLegNum());
We can see that both printed results are true, and data has been shared. Note that shared variables are dependent on the class. In the process of data sharing, to get the class variable, modifying the variable is also the final modification of the class variable.





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.