亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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.

Continuing Learning
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無(wú)標(biāo)題文檔</title> <script>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();</script> </head> <body> </body> </html>
submitReset Code