JavaScript class definition and instantiation

Definition of classes

Strictly speaking, JavaScript is an object-based programming language, not an object-oriented programming language.

In object-oriented programming languages (such as Java, C++, C#, PHP, etc.), declare a class using the class keyword.

For example: public class Person{}

But in JavaScript, there is no keyword to declare a class, and there is no way to control the access rights of the class.

JavaScript uses functions to define classes.

Syntax:
function className(){
// Specific operations
}


For example, define a Person class:

function Person() { this.name=" 张三 "; // 定义一个属性 name this.sex=" 男 "; // 定义一个属性 sex this.say=function(){ // 定义一个方法 say() document.write("嗨!大家好,我的名字是 " + this.name + " ,性别是 " + this.sex + "。"); } }

Explanation: this keyword refers to the current object.

Creating objects (instantiation of classes)

The process of creating objects is also the process of class instantiation.

In JavaScript, creating an object (i.e. instantiation of a class) uses the new keyword.

Syntax:
new className();

Instantiate the above Person class:

var zhangsan=new Person(); zhangsan.say();

Run the code and output the following content:
Hi! Hello everyone, my name is Zhang San and my gender is male.

You can set parameters when defining a class, and you can also pass corresponding parameters when creating an object.

Next, we redefine the Person class:

function Person(name,sex) { this.name=name; // 定义一个属性 name this.sex=sex; // 定义一个属性 sex this.say=function(){ // 定义一个方法 say() document.write("嗨!大家好,我的名字是 " + this.name + " ,性别是 " + this.sex); } } var zhangsan=new Person("小丽","女"); zhangsan.say();

Run the code and output the following content:
Hi! Hello everyone, my name is Xiaoli and my gender is female.

Continuing Learning
||
无标题文档
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!