Lập trình hướng đối tượng trong javascript
Giới thiệu
Nếu mọi người học những ngôn ngữ như Java thì OOP thì đã rất quen thuộc. Trong javascript ta cũng có thể làm như vậy nhờ tính chất closure của javascript
Yêu cầu bắt buộc trước khi đọc
- Hiểu biết về OOP.
- Hiểu biết cơ bản về JS (
function,let...). - Biết closure là gì?
Bắt đầu
Trong Vanila JS chúng ta dùng từ khoá function thay vì class để khai báo
Public properties/ methods
Khai báo một function cùng với các thuộc tính của chúng với keyword là this. Chúng được coi là các public properties/ methods.
function Circle(radius) {
// Public properties
this.radius = radius;
this.draw = () => {
console.log(`draw circle with ${this.radius} radius`);
};
}
// Tạo một object từ khuôn Circle
const circle = new Circle(10);
console.log(circle.radius); // 10
circle.draw(); // draw circle with 10 radiusPrivate properties/ methods
function Circle(radius) {
// Private property (1)
let defaultName = "Circle A";
let count = 0;
// Public properties
this.radius = radius;
this.draw = () => {
count += 1; // thanks to closure (2)
console.log(`draw circle with ${this.radius} radius :: ${count} times`);
};
// Expose private property (3)
Object.defineProperty(this, "defaultName", {
get: () => {
return defaultName;
},
set: (val) => {
defaultName = val;
}
});
}- Khai báo hai thuộc tính bí mật là
defaultNamevàcount. - Dựa vào closure mỗi lần gọi hàm
drawthìcountsẽ thay đổi mà các object bên ngoài hoặc các object thừa kế từclass CircleKhông thể biết được (Tính bí mật nằm ở đây).
// Draw
circle.draw(); // draw circle with 10 radius :: 1 times
circle.draw(); // draw circle with 10 radius :: 2 times
circle.draw(); // draw circle with 10 radius :: 3 times
circle.draw(); // draw circle with 10 radius :: 4 times- Khai báo getter/setter cho thuộc tính bí mật
defaultName.
// default name is not suggested but it is exist
console.log("Before change: ", circle.defaultName);
circle.defaultName = "Circle B";
console.log("After change: ", circle.defaultName);Playground
Đây là example mình đã chuẩn bị cho các bạn chạy cho dễ nhìn
Đọc thêm
Nếu như các bạn chưa hiểu rõ về những đoạn code trên thì tham khảo video.
Comments