Monday, March 17, 2025
Google search engine
spot_img

Tạo đối tượng trong JavaScript

1. Định nghĩa thuộc tính của đối tượng

function student(name,age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
}

Để tạo một Object ta sử dụng phát biểu new. Ví dụ để tạo đối tượng student1
student1 = new student("Bob",10,75);

3 thuộc tính của đối tượng student1 là :
student1.name
student1.age
student1.grade

Ví dụ để tạo đối tượng student2
student2 = new student("Jane",9,82);

Để thêm thuộc tính cho student1 bạn có thể làm như sau:
student1.mother = "Susan"; hoặc bạn có thể định nghĩa lại hàm student

function student(name, age, grade, mother) {
this.name = name;
this.age = age;
this.grade = grade;
this.mother = mother;
}

Đối tượng là thuộc tính của đối tượng khác
Ví dụ:

function grade (math, english, science) {
this.math = math;
this.english = english;
this.science = science;
}
bobGrade = new grade(75,80,77);
janeGrade = new grade(82,88,75);
student1 = new student("Bob",10,bobGrade);
student2 = new student("Jane",9,janeGrade);

student1.grade.math : dùng để lấy điểm Toán của student1
student2.grade.science : dùng lấy điểm môn Khoa học của student2

2. Thêm phương pháp cho đối tượng

function displayProfile() {
document.write("Name: " + this.name + "<BR>");
document.write("Age: " + this.age + "<BR>");
document.write("Mother's Name: " + this.mother + "<BR>");
document.write("Math Grade: " + this.grade.math + "<BR>");
document.write("English Grade: " + this.grade.english + "<BR>");
document.write("Science Grade: " + this.grade.science + "<BR>");
}

function student(name,age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
this.mother = mother;
this.displayProfile = displayProfile;
}

student1.displayProfile();

Ví dụ 1:

<HTML>
<HEAD>
<TITLE>Example 4.3</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- HIDE FROM OTHER BROWSERS
//DEFINE METHOD
function displayInfo() {
document.write("<H1>Employee Profile: " + this.name + "</H1><HR><PRE>");
document.writeln("Employee Number: " + this.number);
document.writeln("Social Security Number: " + this.socsec);
document.writeln("Annual Salary: " + this.salary);
document.write("</PRE>");
}
//DEFINE OBJECT
spot_img

Related Articles