Do cú pháp lớp (class) xuất hiện trong phiên bản ECMAScript 6 trở lên, JavaScript hiện không sử dụng prototype trực tiếp cho nhiều dự án mới.
Nhiều lập trình viên thấy cú pháp lớp dễ hiểu hơn và có một số lợi ích.
Dưới đây là một số lý do chính cho điều này:
Prototype là một cơ chế trong JavaScript được sử dụng để chia sẻ các thuộc tính và phương thức giữa các đối tượng.
Hàm tạo, còn được gọi là hàm tạo, có một thuộc tính mặc định.
Các đối tượng được tạo bởi hàm tạo đó sẽ kế thừa các thuộc tính và phương thức từ thuộc tính.
Theo như cách hiểu của tôi là bạn có thể tạo 1 phương thức mà các class được set có thể kế thừa phương thức đó.
Bạn có thể xem các ví dụ bên dưới.
Một đối tượng mà các đối tượng khác có thể kế thừa các thuộc tính và phương thức.
Một đối tượng được tạo từ một hàm tạo sẽ có một liên kết ẩn (được gọi là [[Prototype]]) của hàm tạo đó.
JavaScript sẽ tìm kiếm thuộc tính hoặc phương thức của đối tượng khi bạn truy cập nó.
Nếu không thể tìm thấy, nó sẽ tiếp tục tìm kiếm trong prototype của đối tượng.
Theo chuỗi, quy trình này tiếp tục cho đến khi tìm thấy thuộc tính hoặc đến cuối chuỗi (tới null).
Điều này cho phép các đối tượng chia sẻ hiệu quả các thuộc tính và phương thức.
Chúng tôi tạo một phương thức getSummary và đưa nó vào Book.
prototype.
Phương thức này có thể được sử dụng cho tất cả các đối tượng trong sách, không cần phải tạo lại nó cho mỗi đối tượng.
function Book(title, author, year) { this.title = title; this.author = author; this.year = year; } Book.prototype.getSummary = function() { return `${this.title} was written by ${this.author} in ${this.year}.`; }; const book1 = new Book('To Kill a Mockingbird', 'Harper Lee', 1960); console.log(book1.getSummary()); // Output: To Kill a Mockingbird was written by Harper Lee in 1960.
Gender được thêm vào người, nghĩa là tất cả các đối tượng Person đều có đặc điểm này.
Điều này giúp tiết kiệm bộ nhớ khi mọi đối tượng đều có những thuộc tính chung.
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.gender = 'Unknown'; const person1 = new Person('Alice', 30); console.log(person1.gender); // Output: Unknown person1.gender = 'Female'; console.log(person1.gender); // Output: Female
Dog kế thừa Animal bằng cách sử dụng Object.
create để tạo liên kết giữa Dog.
prototype và Animal.
prototype.
Điều này cho phép đối tượng Con chó sử dụng cả phong cách nói chuyện của động vật và phong cách chào của nó.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(`${this.name} makes a noise.`); }; function Dog(name, breed) { Animal.call(this, name); this.breed = breed; } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.bark = function() { console.log(`${this.name} barks.`); }; const dog1 = new Dog('Rex', 'German Shepherd'); dog1.speak(); // Output: Rex makes a noise. dog1.bark(); // Output: Rex barks.
Để trả về phần tử cuối cùng của mảng, thêm một phương thức last mới vào Array.
Điều này tăng cường khả năng hoạt động của mảng mà không cần thay đổi mã JavaScript nguồn gốc.
Array.prototype.last = function() { return this[this.length - 1]; }; const numbers = [1, 2, 3, 4, 5]; console.log(numbers.last()); // Output: 5
hasOwnProperty xác định liệu thuộc tính có tồn tại trực tiếp trên đối tượng hay không bằng cách sử dụng chuỗi prototype.
Toán tử in kiểm tra xem thuộc tính có tồn tại trong đối tượng, bao gồm cả trong chuỗi prototype hay không.
function Car(make, model) { this.make = make; this.model = model; } Car.prototype.getDetails = function() { return `${this.make} ${this.model}`; }; const car1 = new Car('Toyota', 'Corolla'); console.log(car1.hasOwnProperty('make')); // Output: true console.log(car1.hasOwnProperty('getDetails')); // Output: false console.log('getDetails' in car1); // Output: true
Cú pháp lớp trong ES6 dễ hiểu và rõ ràng hơn so với việc sử dụng trực tiếp.
Điều này cải thiện khả năng đọc và bảo trì của code.
// Class syntax class Book { constructor(title, author, year) { this.title = title; this.author = author; this.year = year; } getSummary() { return `${this.title} was written by ${this.author} in ${this.year}.`; } } // Creating an instance const book1 = new Book('To Kill a Mockingbird', 'Harper Lee', 1960); console.log(book1.getSummary()); // Output: To Kill a Mockingbird was written by Harper Lee in 1960.
Chi tiết hơn
// Parent class class Book { constructor(title, author, year) { this.title = title; this.author = author; this.year = year; } getSummary() { return `${this.title} was written by ${this.author} in ${this.year}.`; } } // Subclass class Magazine extends Book { constructor(title, author, year, month) { super(title, author, year); this.month = month; } getSummary() { return `${super.getSummary()} (published in ${this.month})`; } } // Creating an instance const mag1 = new Magazine('National Geographic', 'Various', 2020, 'June'); console.log(mag1.getSummary()); // Output: National Geographic was written by Various in 2020. (published in June)
Mặc dù vẫn là một phần quan trọng của JavaScript, cú pháp lớp trong ES6 đã giúp người dùng dễ tiếp cận hơn, đặc biệt là đối với những người đến từ các ngôn ngữ lập trình hướng đối tượng khác.
Để làm việc sâu hơn với JavaScript và hiểu rõ hơn về cách nó hoạt động ở cấp độ nền tảng, vẫn cần phải hiểu.
Ví dụ về việc sử dụng để tạo một ApiClient trong JavaScript, giúp bạn thực hiện các yêu cầu HTTP hiệu quả được trình bày dưới đây.
function ApiClient(baseURL) { this.baseURL = baseURL; } ApiClient.prototype.get = function(endpoint) { return fetch(this.baseURL + endpoint) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); }; ApiClient.prototype.post = function(endpoint, data) { return fetch(this.baseURL + endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); };
Cách dùng
const apiClient = new ApiClient('https://jsonplaceholder.typicode.com'); // Sử dụng phương thức GET apiClient.get('/posts/1') .then(data => console.log(data)) .catch(error => console.error(error)); // Sử dụng phương thức POST const newPost = { title: 'foo', body: 'bar', userId: 1 }; apiClient.post('/posts', newPost) .then(data => console.log(data)) .catch(error => console.error(error));
Cách sử dụng để mở rộng chức năng của đối tượng trong JavaScript được minh họa trong ví dụ trên.
Điều này giúp bạn xây dựng một ApiClient linh hoạt và tái sử dụng.
#Mtips5s #Contact
Fanpage: https://www.facebook.com/mtipscoder
Group trao đổi, chia sẻ: https://www.facebook.com/groups/mtipscoder
Website: https://mtips5s.com
Youtube: https://mtips5s.com
Twitter(X): @takagiks99
Instagram: @khuongkara
Threads: @khuongkara
Google Maps: @khuongkara
#Base Code #Souce Code
Npm: @tools.mtips5s.com
Bộ công cụ My Self: @github
Npm: @npm
Docker: @docker
Chúc các bạn thành công!
Leave A Comment