The examples in this article describe how classes are defined in JavaScript. Share to everyone for your reference, specific as follows:
JavaScript itself does not support object-oriented, it does not have an access control character, it does not define the class's keyword class, it does not support inherited extend or colons, nor does it support virtual functions, but JavaScript is a flexible language, Let's take a look at how JavaScript, without the keyword class, implements the class definition and creates objects.
First, define the class and create an instance object of the class
In JavaScript, we use function to define a class, as follows:
function Shape ()
{
var x = 1;
var y = 2;
}
You might say, suspect? Isn't this the definition function? Yes, this is the definition function, we define a shape function and initialize x and Y. However, if you look at it from a different perspective, this defines a shape class that has two attributes X and Y, and the initial values are 1 and 2, except that we define the class's keyword as a function rather than class.
Then, we can create the object Ashape of the shape class, as follows:
Copy Code code as follows:
var ashape = new Shape ();
Ii. defining public and private properties
We've created the Ashape object, but when we try to access its properties, we get an error, as follows:
Copy Code code as follows:
This indicates that the attribute defined with VAR is private. We need to use the This keyword to define public properties
function Shape ()
{this
. x = 1;
this. y = 2;
}
In this way, we can access the properties of shape, such as.
Copy Code code as follows:
OK, we can sum it up according to the above code: use Var to define the private property of the class, and use this to define the public property of the class.
Iii. defining public and private methods
In JavaScript, functions are instances of function classes, and functions are indirectly inherited from object, so a function is also an object, so we can use the assignment method to create a function, of course, we can also assign a function to a property variable of a class, This property variable can be called a method because it is a function that can be executed. The code is as follows:
function Shape ()
{
var x = 0;
var y = 1;
this. Draw = function ()
{
//print;
};
}
We define a draw in the above code and assign a function to it, and we can call this function through Ashape, which is called a public method in OOP, such as:
Copy Code code as follows:
If defined with Var, the draw becomes private, and OOP is called a private method, such as
function Shape ()
{
var x = 0;
var y = 1;
var draw = function ()
{
//print;}
;
}
This way, you can't use Ashape.draw to invoke this function.
Third, the constructor
JavaScript does not support OOP, and of course there is no constructor, but we can simulate a constructor on our own, let the object be invoked automatically when it is created, the following code:
function Shape ()
{
var init = function ()
{
//constructor code
};
Init ();
}
At the end of shape, we call the init function artificially, then, when we create a Shape object, init is always invoked automatically, and we can simulate our constructor.
Four, the constructor with the parameter
How do I get a constructor with arguments? In fact, it is very simple to write the arguments passed in to the function's argument list, as
function Shape (Ax,ay)
{
var x = 0;
var y = 0;
var init = function ()
{
//constructor
x = ax;
y = ay;
};
Init ();
}
That way, we can create objects like this:
Copy Code code as follows:
var ashape = new Shape (0, 1);
V. Static properties and Static methods
How do you define static properties and methods in JavaScript? 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 property count, which belongs to the class and is not object-owned.
Shape.staticmethod = function () {};//define a static method
With the static properties and methods, we can access it with the class name, as follows
alert (ashape.count);
Ashape.staticmethod ();
Note: Static properties and methods are public, so far I don't know how to make static properties and methods private.
Accessing public and private properties of this class in a method
To access your own properties in the method of a class, JavaScript has different access methods for public and private properties, please look at the following code
function Shape (Ax,ay)
{
var x = 0;
var y = 0;
this. GX = 0;
this. gy = 0;
var init = function ()
{
x = ax;//access private property, directly write variable name can
y = ay;
this. GX = ax; To access the public property, you need to precede the variable name with this.
this. gy = ay;
Init ();
}
Vii. Considerations for this
According to the author's experience, this does not always point to the object itself, primarily because JavaScript is not an OOP language, and functions and classes are defined by function, which can cause minor problems.
This pointer refers to the wrong situation generally on the event processing, we want to have an object's member function to respond to an event, when the event is triggered, the system will call our member function, but, the incoming this pointer is not our own object, of course, Then call this in the member function, of course, there will be an error.
The solution is that we save this to a private property at the beginning of the definition class, and later we can use this property instead of this. I used this method to use this pointer quite safe, and it is very easy to
Let's revise the code to solve this problem. Look at the code in section six, you'll understand.
function Shape (Ax,ay)
{
var _this = this;//save this, replace this with _this in the future, so you don't get dizzy by this.
var x = 0;
var y = 0;
_THIS.GX = 0;
_this.gy = 0;
var init = function ()
{
x = ax;//access private property, directly write variable name can
y = ay;
_THIS.GX = ax; To access the public property, you need to precede the variable name with this.
_this.gy = ay;
};
Init ();
}
We talked about how to define classes in JavaScript, create objects of classes, create public and private properties and methods, create static properties and methods, simulate constructors, and discuss this error prone.
On the OOP implementation in JavaScript here is the most practical content, generally use JavaScript to define the class, the creation of objects with the above code is enough. Of course, you can also use MooTools or prototype to define classes and create objects. I've used the MooTools framework, it feels good, it's more perfect for JavaScript class simulations, and it supports class inheritance, and interested readers can try. Of course, if you use a framework, you need to include the relevant JS headers in your Web page, so I still want readers to be able to create classes without frames, so that the code is more efficient, and you can see that creating a simple class is not a hassle.
Add:
Four ways to define JavaScript classes:
1, Factory mode 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+ "<br>");
};
return tempcar;
var car1=new createcar ("Factory Santana", "Red", "121313");
Car1.getname (); /* Defines a factory function that can create and return a particular type of object, which looks good, but there is a small problem with creating a new function Showcolor every time we call it, we can move it outside the function getName () {document.write T
his.name+ "-----" +this.color+ "<br>");
Point directly to it in the factory function tempcar.getname = GetName;
This avoids the problem of duplicating the function, but it does not look like an object's approach.
*///2, constructor method function car (name,color,price) {this.name=name;
This.color=color;
This.price=price;
This.getcolor=function () {document.write (this.name+ "-----" +this.color+ "<br>");
};
var car2=new car ("Structural Santana", "Red", "121313");
Car2.getcolor ();
/* You can see the difference from the first way, there is no create object inside the constructor, but use the This keyword.
When you call a constructor with new, you create an object and then use this to access it.
This usage is similar to other object-oriented languages, but it has the same problem with the previous one, that is, repeating the creation of functions. *///3, prototype mode function Procar () {} PROCAR.PROTOTYPE.NAme= "Prototype";
Procar.prototype.color= "Blue";
Procar.prototype.price= "10000";
Procar.prototype.getname=function () {document.write (this.name+ "-----" +this.color+ "<br>");
var car3=new procar ();
Car3.getname (); /* First defines the constructor car, but no code, and then adds the property through prototype. Advantages: A. All instances hold pointers to Showcolor, which solves the problem of duplicate creation of functions B. You can check object type alert (Car3 instanceof Procar) with instanceof;//true disadvantage, add down
Surface 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, p
All two instances of Rocar point to the same array.
*///4, dynamic prototype mode 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+ "<br>");
};
Autoprocar.initialized=true; } var car4=new autoprocar ("Dynamic Prototype", "YelLow "," 1234565 ");
Car4.getname ();
Car4.drives.push ("Newone");
document.write (car4.drives);
/* This way is my favorite, all class definitions are done in a function, looks very much like the class definition of other languages, do not duplicate the creation of functions, you can also use instanceof/
I hope this article will help you with your JavaScript programming.