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=" 張三 "; // 定義一個(gè)屬性 name this.sex=" 男 "; // 定義一個(gè)屬性 sex this.say=function(){ // 定義一個(gè)方法 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; // 定義一個(gè)屬性 name this.sex=sex; // 定義一個(gè)屬性 sex this.say=function(){ // 定義一個(gè)方法 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.