Danh mục : Javascript

Bài 4: TẠO ĐỐI TƯỢNG TRONG JAVASCRIPT

TẠO ĐỐI TƯỢNG TRONG JAVASCRIPT

Bài 4: 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
MTWRFSS 4
function student(name, age, grade, mother) {
this.name = name;
this.age = age;
this.grade = grade;
this.mother = mother;
}
JAVASCRIPT MEDIASPACE CLUB (HTD) PAGE: 13
Đố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 + “
”);
document.write(“Age: “ + this.age + “
”);
document.write(“Mother’s Name: “ + this.mother + “
”);
document.write(“Math Grade: “ + this.grade.math + “
”);
document.write(“English Grade: “ + this.grade.english + “
”);
document.write(“Science Grade: “ + this.grade.science + “
”);
}
function student(name,age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
this.mother = mother;
this.displayProfile = displayProfile;
}
student1.displayProfile();
Ví du:
4

 

 

 





 


 

 


Vi du:

Trong phần body bạn có thể xuất ra dạng như sau:

 

 



Tags