This article mainly introduces the method of defining classes in JavaScript, analyzes the implementation of object-oriented classes in JavaScript in the form of examples, and provides related skills. It also includes four types of defining JavaScript classes, for more information about how to define classes in JavaScript, see the examples in this article. We will share this with you for your reference. The details are as follows:
Javascript itself does not support object-oriented features. It does not have an access control operator and does not define the class keyword. It does not support inherited extend or colons, nor does it support virtual functions, however, Javascript is a flexible language. Let's take a look at how Javascript without a keyword class implements class definition and creates objects.
I. Define a class and create an instance object for the class
In Javascript, we use functions to define classes, as shown below:
function Shape(){var x = 1 ;var y = 2 ;}
You might say, suspect? Isn't this a definition function? Yes, this is the definition function. We have defined a Shape function and initialized x and y. However, from another perspective, this is to define a Shape class, which has two attributes x and y. The initial values are 1 and 2,, we define that the key word of a class is function rather than class.
Then, we can create the aShape object of the Shape class, as shown below:
The Code is as follows:
Var aShape = new Shape ();
Ii. Define public and private attributes
We have created an aShape object. However, when we try to access its attributes, an error occurs, as shown below:
The Code is as follows:
AShape. x = 1;
This indicates that the property defined with var is private. We need to use the this keyword to define public attributes.
function Shape(){this .x = 1 ;this .y = 2 ;}
In this way, we can access the Shape attributes, for example.
The Code is as follows:
AShape. x = 2;
Well, we can conclude from the code above that var can be used to define the private attribute of the class, while this can be used to define the public attribute of the class.
3. Define public and private methods
In Javascript, a Function is an instance of the Function class. A Function indirectly inherits from an Object. Therefore, a Function is also an Object. Therefore, we can create a Function by assigning values. Of course, we can also assign a function to an attribute variable of the class. This attribute variable can be called a method because it is a executable function. The Code is as follows:
function Shape(){var x = 0 ;var y = 1 ;this .draw = function (){// print; };}
In the above Code, we define a draw and assign a function to it. Below, we can call this function through aShape, which is called a public method in OOP, for example:
The Code is as follows:
AShape. draw ();
If var is used, the draw becomes private. in OOP, it is called a private method, as shown in
function Shape(){var x = 0 ;var y = 1 ;var draw = function (){// print; };}
In this way, you cannot use aShape. draw to call this function.
Iii. Constructor
Javascript does not support OOP, and of course there is no constructor. However, we can simulate a constructor by ourselves to make the object automatically called when it is created. The Code is as follows:
Function Shape () {var init = function () {// constructor code}; init ();}
At the end of the Shape, we manually call the init function, so when we create a Shape object, init will always be automatically called to simulate our constructor.
Iv. constructors with Parameters
How can a constructor contain parameters? In fact, it is very easy to write the parameters to be passed in to the parameter list of the function, as shown in figure
Function Shape (ax, ay) {var x = 0; var y = 0; var init = function () {// constructor x = ax; y = ay ;}; init ();}
In this way, we can create an object as follows:
The Code is as follows:
Var aShape = new Shape (0, 1 );
V. Static attributes and static methods
In Javascript, how do I define static attributes and methods? As shown below
Function Shape (ax, ay) {var x = 0; var y = 0; var init = function () {// constructor x = ax; y = ay ;}; init ();} Shape. count = 0; // defines a static attribute count, which belongs to a class rather than an object. Shape. staticMethod = function () {}; // defines a static method.
With static attributes and methods, we can use the class name to access it, as shown below:
alert ( aShape.count );aShape.staticMethod();
Note: static attributes and methods are both public. So far, I have no idea how to make static attributes and Methods private ~
6. Access the Public and Private attributes of the class in the Method
Access your own attributes in the class method. Javascript has different access methods for Public and Private attributes. Please refer to the following code.
Function Shape (ax, ay) {var x = 0; var y = 0; this. gx = 0; this. gy = 0; var init = function () {x = ax; // you can directly write the variable name to access the private property. gx = ax; // to access public attributes, you must add this before the variable name. this. gy = ay;}; init ();}
7. Considerations for this
Based on my experience, this in a class does not always point to our object. The main reason is that Javascript is not an OOP language, and function and class are defined by function, of course it will cause some minor problems.
This pointer indicates an error in event processing. We want a member function of an object to respond to an event. When an event is triggered, the system will call this member function, however, the passed this pointer is no longer our own object. Of course, an error will occur when we call this in the member function.
The solution is to save this to a private attribute at the beginning of the definition class. Later, we can use this attribute to replace this. Using this method is quite safe and worry-free ~
Let's modify the code to solve this problem. Check the code in Part 6 and you will understand it.
Function Shape (ax, ay) {var _ this = this; // save this and use _ this instead of this, in this way, var x = 0; var y = 0; _ this. gx = 0; _ this. gy = 0; var init = function () {x = ax; // access the private property and directly write the variable name to y = ay; _ this. gx = ax; // to access public attributes, you must add this before the variable name. _ this. gy = ay;}; init ();}
We talked about how to define classes in Javascript, create class objects, create public and private attributes and methods, create static attributes and methods, and simulate constructors, and discussed the error-prone this.
As for the implementation of OOP in Javascript, the above is the most practical content. Generally, classes are defined using Javascript, and the above Code is enough to create objects. Of course, you can also use mootools or prototype to define classes and create objects. I have used the mootools framework and I feel very good. It has improved the Javascript class simulation and supports class inheritance. Interested readers can try it. Of course, if you use a framework, you need to include relevant js header files in your webpage. Therefore, I still hope that the reader can create classes without a framework. In this way, code efficiency is high, and you can also see that it is not difficult to create a simple class ~
Supplement:
The following four methods are defined for JavaScript:
// 1. factory function createCar (name, color, price) {var tempcar = new Object; tempcar. name = name; tempcar. color = color; tempcar. price = price; tempcar. getName = function () {document. write (this. name + "-----" + this. color +"
") ;}; Return tempcar;} var car1 = new createCar (" factory santana "," red "," 121313 "); car1.getName (); /* defines a factory function that can create and return a specific type of object. It looks good, but there is a small problem. Create a new function showColor every time you call it, we can move it out of the function, function getName () {document. write (this. name + "-----" + this. color +"
");} Direct to tempCar. getName = getName in the factory function. This avoids the problem of duplicate function creation, but it does not look like an object method. * // 2. function Car (name, color, price) {this. name = name; this. color = color; this. price = price; this. getColor = function () {document. write (this. name + "-----" + this. color +"
") ;};} Var car2 = new Car (" construct santana "," red "," 121313 "); car2.getColor (); /* you can see the difference from the first method. No object is created in the constructor, but this keyword is used. When calling the constructor using new, an object is created first, and then accessed using this. This method is similar to other object-oriented languages, but this method has the same problem as the previous one, that is, repeated function creation. * // 3. Prototype function proCar () {} proCar. prototype. name = "prototype"; proCar. prototype. color = "blue"; proCar. prototype. price = "10000"; proCar. prototype. getName = function () {document. write (this. name + "-----" + this. color +"
") ;}; Var car3 = new proCar (); car3.getName ();/* first defines the constructor Car, but there is no code, and then adds attributes through prototype. Advantage:. all instances store the pointer to showColor, which solves the problem of repeated function creation. you can use instanceof to check the disadvantage of the object type alert (car3 instanceof proCar); // true, add the following code: proCar. prototype. drivers = newArray ("mike", "sue"); car3.drivers. push ("matt"); alert (car3.drivers); // outputs "mike, sue, matt" alert (car3.drivers); // outputs "mike, sue, matt "drivers is a pointer to an Array object. Both instances of proCar point to the same Array. * // 4. Dynamic Prototype function autoProCar (name, color, price) {this. name = name; this. color = color; this. price = price; this. drives = new Array ("mike", "sue"); if (typeof autoProCar. initialized = "undefined") {autoProCar. prototype. getName = function () {document. write (this. name + "-----" + this. color +"
") ;}; AutoProCar. initialized = true;} var car4 = new autoProCar ("Dynamic Prototype", "yellow", "1234565"); car4.getName (); car4.drives. push ("newOne"); document. write (car4.drives);/* This method is my favorite. All class definitions are completed in one function. It looks very similar to the class definitions in other languages and does not create functions repeatedly, you can also use instanceof */
I hope this article will help you design JavaScript programs.