


Detailed explanation of javascript definition classes and implementation examples of classes_javascript skills
The examples in this article describe the implementation of javascript definition classes and classes. Share it with everyone for your reference, the details are as follows:
Recently, I often see people asking in several groups how a function in a class calls this. method that is exposed after being defined. Now I have an essay on class implementation.
First let’s talk about classes. In a class we will have the following characteristics:
1. Public methods
2. Private methods
3. Attributes
4. Private variables
5. Destructor
Let’s look at an example directly:
/***定义类***/ var Class = function(){ var _self = this;//把本身引用负值到一变量上 var _Field = "Test Field"; //私有字段 var privateMethod = function(){ //私有方法 alert(_self.Property); //调用属性 } this.Property = "Test Property"; //公有属性 this.Method = function(){ //公有方法 alert(_Field); //调用私用字段 privateMethod(); //调用私用方法 } }
I have written all the notes here, so everyone can probably understand them at a glance. For friends who rarely write JS, you may wonder why I define a _self variable, because in js, this does not need to be used in other object languages, and this will change during its parsing and running processes. Here I will briefly talk about the definition of this in js. I can write more if necessary.
Definition: this is the object to which the function containing it belongs when it is called as a method.
Features: The environment of this can change as the function is assigned to different objects!
Interested friends can search for information online to learn more. Back to the topic, the purpose of _self here is to open an additional private variable and point the reference directly to the class itself.
I just mentioned a destructor issue, which can be implemented directly using code. Just write the execution code directly at the end of the function.
/***定义类***/ var Class = function(){ var _self = this;//把本身引用负值到一变量上 var _Field = "Test Field"; //私有字段 var privateMethod = function(){ //私有方法 alert(_self.Property); //调用属性 } this.Property = "Test Property"; //公有属性 this.Method = function(){ //公有方法 alert(_Field); //调用私用字段 privateMethod(); //调用私用方法 } /***析构函数***/ var init = function(){ privateMethod(); } init(); }
Use this class
var c = new Class(); c.Method(); //使用方法
That’s OK
Javascript itself does not support object-oriented, it has no access control characters, it does not have the keyword class to define a class, it does not support extend or colon for inheritance, and it does not use virtual to support virtual functions. However, Javascript is A flexible language, let's take a look at how Javascript without the keyword class implements class definition and creates objects.
1: Define a class and create an instance object of the class
In Javascript, we use functions to define classes, as follows:
function Shape() { var x=1; var y=2; }
You might say, doubt? Isn't this a defining function? Yes, this is a definition function. We define a Shape function and initialize x and y. However, if you look at it from another angle, this is to define a Shape class, which has two attributes x and y, and the initial values are 1 and 2 respectively. However, the keyword we use to define the class is function instead of class.
Then, we can create an object aShape of the Shape class, as follows:
Two: Define public attributes and private attributes
We have created the aShape object, but when we try to access its properties, an error occurs, as follows:
This shows that properties defined with var are private. We need to use this keyword to define public attributes
function Shape() { this.x=1; this.y=2; }
In this way, we can access the attributes of Shape, such as.
Well, we can summarize based on the above code: use var to define the private attributes of the class, and use this to define the public attributes of the class.
3: Define public methods and private methods
In Javascript, a function is an instance of the Function class. Function indirectly inherits from Object. Therefore, a function is also an object. Therefore, we can use the assignment method to create a function. Of course, we can also assign a function to a class. An attribute variable, then this attribute variable can be called a method because it is an executable function. The code is as follows:
function Shape() { var x=0; var y=1; this.draw=function() { //print; }; }
We defined a draw in the above code and assigned a function to it. Next, we can call this function through aShape, which is called a public method in OOP, such as:
If defined with var, then the draw becomes private, which is called a private method in OOP, such as
function Shape() { var x=0; var y=1; var draw=function() { //print; }; }
这样就不能使用aShape.draw调用这个函数了。
三:构造函数
Javascript并不支持OOP,当然也就没有构造函数了,不过,我们可以自己模拟一个构造函数,让对象被创建时自动调用,代码如下:
function Shape() { var init = function() { //构造函数代码 }; init(); }
在Shape的最后,我们人为的调用了init函数,那么,在创建了一个Shape对象是,init总会被自动调用,可以模拟我们的构造函数了。
四:带参数的构造函数
如何让构造函数带参数呢?其实很简单,将要传入的参数写入函数的参数列表中即可,如
function Shape(ax,ay) { var x=0; var y=0; var init = function() { //构造函数 x=ax; y=ay; }; init(); }
这样,我们就可以这样创建对象:
五:静态属性和静态方法
在Javascript中如何定义静态的属性和方法呢?如下所示
function Shape(ax,ay) { var x=0; var y=0; var init = function() { //构造函数 x=ax; y=ay; }; init(); } Shape.count=0;//定义一个静态属性count,这个属性是属于类的,不是属于对象的。 Shape.staticMethod=function(){};//定义一个静态的方法
有了静态属性和方法,我们就可以用类名来访问它了,如下
alert ( aShape.count ); aShape.staticMethod();
注意:静态属性和方法都是公有的,目前为止,我不知道如何让静态属性和方法变成私有的
六:在方法中访问本类的公有属性和私有属性
在类的方法中访问自己的属性,Javascript对于公有属性和私有属性的访问方法有所不同,请大家看下面的代码
function Shape(ax,ay) { var x=0; var y=0; this.gx=0; this.gy=0; var init = function() { x=ax;//访问私有属性,直接写变量名即可 y=ay; this.gx=ax;//访问公有属性,需要在变量名前加上this. this.gy=ay; }; init(); }
七:this的注意事项
根据笔者的经验,类中的this并不是一直指向我们的这个对象本身的,主要原因还是因为Javascript并不是OOP语言,而且,函数和类均用function定义,当然会引起一些小问题。
this指针指错的场合一般在事件处理上面,我们想让某个对象的成员函数来响应某个事件,当事件被触发以后,系统会调用我们这个成员函数,但是,传入的this指针已经不是我们本身的对象了,当然,这时再在成员函数中调用this当然会出错了。
解决方法是我们在定义类的一开始就将this保存到一个私有的属性中,以后,我们可以用这个属性代替this。我用这个方法使用this指针相当安全,而且很是省心~
我们修改一下代码,解决this问题。对照第六部分的代码看,你一定就明白了
function Shape(ax,ay) { var _this=this; //把this保存下来,以后用_this代替this,这样就不会被this弄晕了 var x=0; var y=0; _this.gx=0; _this.gy=0; var init = function() { x=ax;//访问私有属性,直接写变量名即可 y=ay; _this.gx=ax;//访问公有属性,需要在变量名前加上this. _this.gy=ay; }; init(); }
希望本文所述对大家JavaScript程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
