search
HomeWeb Front-endJS TutorialDetailed 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:

Copy code The code is as follows:
var aShape = new Shape();

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:

Copy code The code is as follows:
aShape.x=1;

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.

Copy code The code is as follows:
aShape.x=2;

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:

Copy code The code is as follows:
aShape.draw();

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();
}

这样,我们就可以这样创建对象:

复制代码 代码如下:
var aShape = new Shape(0,1);

五:静态属性和静态方法

在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程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use