Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?

Trong bài đăng trên blog này, tôi sẽ hướng dẫn bạn một ví dụ thực tế sử dụng khái niệm lớp trong Javascript

Tôi nghĩ sẽ hữu ích khi làm việc với trường hợp sử dụng thực tế vì việc hiểu các khái niệm sẽ đơn giản hơn nhiều khi bạn có thể liên hệ chúng với cuộc sống thực

Vì vậy, trong hướng dẫn này, bạn sẽ tìm hiểu về các lớp trong JavaScript, tính kế thừa, hàm trừu tượng, cách sử dụng các từ khóa như

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
4 và
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
5s, từ khóa tĩnh và các thành viên riêng của lớp

Hãy đi sâu vào

Mục lục

điều kiện tiên quyết

Trước khi bạn bắt đầu đọc bài đăng trên blog này, bạn nên có hiểu biết cơ bản về các chủ đề sau

  • sơ đồ lớp. Chúng tôi sẽ sử dụng chúng để giới thiệu ví dụ của chúng tôi
  • Giới thiệu hàm tạo trong JS

Các lớp trong JavaScript là gì?

Các lớp đã được giới thiệu trong EcmaScript 2015 (ES6) để cung cấp một cách rõ ràng hơn để tuân theo các mẫu lập trình hướng đối tượng

JavaScript vẫn theo mô hình kế thừa dựa trên nguyên mẫu. Các lớp trong JavaScript là đường cú pháp trên mô hình kế thừa dựa trên nguyên mẫu mà chúng tôi sử dụng để triển khai các khái niệm OOP

Do đó, việc giới thiệu các lớp trong JS giúp các nhà phát triển xây dựng phần mềm xung quanh các khái niệm OOP dễ dàng hơn. Nó cũng mang những điểm tương đồng với các ngôn ngữ lập trình dựa trên OOP khác như C ++ và Java

Trước các lớp học, chúng tôi đã sử dụng các hàm xây dựng để thực hiện OOP trong JavaScript. Hãy xem ví dụ dưới đây

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");
console.log(pen1);
Hàm xây dựng bút

Đoạn mã trên hiển thị một hàm xây dựng

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
6 có các thuộc tính tên, màu sắc và giá cả. Chúng tôi đang sử dụng từ khóa
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
7 với hàm tạo
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
6 để tạo một đối tượng
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
9.  

Bây giờ, giả sử chúng ta muốn thêm một hàm mới vào hàm tạo

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
6. Để làm điều này, chúng ta cần thêm hàm vào thuộc tính nguyên mẫu của
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
6. Hãy xem hàm
class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
2 bên dưới

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
Thêm chức năng trong hàm tạo

Nếu những khái niệm này không có ý nghĩa với bạn, thì tôi khuyên bạn nên trau dồi kiến ​​thức cơ bản/JS của mình thông qua các bài viết được đề cập trong phần Điều kiện tiên quyết. Đặc biệt, hãy xem bài viết về Prototype và hàm Constructor

Nhìn vào đoạn mã trên, chúng ta có thể nói rằng chúng ta đã làm được những gì chúng ta muốn làm – đó là thêm một hàm

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
2 vào hàm tạo
function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
6. Nhưng bạn có thể thấy rằng nó không dễ đọc như vậy so với các khái niệm OOP mà chúng tôi triển khai trong C++ hoặc Java

Chúng ta có thể tạo lại ví dụ trên với sự trợ giúp của từ khóa

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
5. Hãy nhìn vào đoạn mã dưới đây

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
Sử dụng từ khóa Class trong JS

Nhận thấy sự khác biệt. Chúng tôi đã đạt được kết quả tương tự nhưng với cú pháp rõ ràng hơn nhiều. Việc thêm một hàm thành viên mới như

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
2 dễ dàng hơn nhiều so với việc thêm một hàm trực tiếp vào nguyên mẫu của hàm tạo

Hãy đi sâu hơn vào các lớp trong JS bằng cách sử dụng một trường hợp sử dụng ví dụ. Với trường hợp sử dụng này, chúng ta sẽ xem những khái niệm này có thể hữu ích như thế nào để giải quyết một số vấn đề thực tế

Mô tả trường hợp sử dụng

Chỉ cần một lưu ý nhanh chóng. các sơ đồ Ngữ cảnh, Vùng chứa và Lớp được vẽ trong bài đăng trên blog này không tuân theo chính xác các quy ước của các sơ đồ trên. Tôi đã tính gần đúng các sơ đồ để giúp bạn hiểu các khái niệm nói chung

Trước khi bắt đầu, tôi khuyên bạn nên đọc các mô hình c4, sơ đồ bộ chứa và sơ đồ ngữ cảnh nếu bạn cần xem lại. Bạn có thể tìm thấy chúng trong phần điều kiện tiên quyết

Chúng ta sẽ giải bài toán sau. giúp người bán hàng phân loại ghế trong kho của họ và hiển thị chúng trên màn hình

Trường hợp sử dụng đơn giản và khá dễ hiểu. Hãy xem sơ đồ bên dưới thể hiện toàn bộ hệ thống được đề xuất

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Sơ đồ ngữ cảnh cho hệ thống quản lý ghế

Như bạn có thể thấy từ sơ đồ trên, có 3 thành phần chính

  1. Người. Chủ cửa hàng sẽ tương tác với hệ thống của chúng tôi
  2. Hệ thống phần mềm. Cổng giao diện kho - Đây là giao diện cho phép chủ cửa hàng xem hoặc sửa thông tin ghế có trong kho
  3. Hệ thống phần mềm. Hệ thống quản lý ghế - Hệ thống này sẽ cho phép giao diện tìm nạp hoặc sửa đổi các chi tiết cần thiết theo yêu cầu của chủ cửa hàng

Bây giờ chúng ta đã hiểu trường hợp sử dụng, hãy bắt đầu với hệ thống mục tiêu mà chúng ta sẽ tập trung vào trong bài đăng trên blog này. Đó là hệ thống quản lý ghế

Chúng tôi sẽ bắt đầu bằng cách tạo một số thành phần chính trong Hệ thống quản lý ghế của chúng tôi. Các thành phần của chúng tôi trong hệ thống này chỉ là các lớp khác nhau sẽ giúp tạo điều kiện thuận lợi cho các nhu cầu khác nhau của chủ cửa hàng

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Thành phần ghế của Hệ thống quản lý ghế

Hãy thêm một thành phần có tên là

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7. Vì là class nên nó sẽ có các thuộc tính (properties) và hành vi (method) riêng

Hãy nhìn vào sơ đồ trên. Chúng tôi có thể thấy điều đó

  • Hàng thứ hai chứa các thuộc tính của lớp ghế, ví dụ: màu sắc, chiều cao ghế, góc ngả, v.v.
  • Hàng thứ ba tương ứng với các phương thức cho chúng ta biết những chức năng mà ghế có thể thực hiện, ví dụ như điều chỉnhSeatHeight, điều chỉnhAngle, di chuyểnChair, v.v.

Chúng tôi sẽ làm theo cách trình bày ở trên cho tất cả các thành phần mà chúng tôi sẽ tạo trong suốt bài viết này

Thành phần

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 sẽ là thành phần cơ sở của chúng ta. Điều này có nghĩa là tất cả các loại ghế khác như ghế văn phòng, ghế ăn, v.v. sẽ thuộc loại/thành phần này

Hãy bắt đầu bằng cách tạo lớp ghế cơ sở của chúng ta trong JS. Hãy nhìn vào đoạn mã dưới đây

class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = backSupport;
        this.headSupport = headSupport;
        this.padding = padding;
        this.armRests = armRests;
        this.seatSize = seatSize;
        this.isHeightAdjustable = isHeightAdjustable;
        this.isMovable = isMovable;
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);

console.dir("Chair Prototype", Chair);
console.log("Chair Object", newChair);
Chủ tịch lớp cơ bản

Lớp chủ nhiệm có các thành viên sau

  • Thuộc tính. Chúng sẽ xác định các thuộc tính của ghế như màu sắc, chiều cao ghế, Hỗ trợ lưng, v.v.
  • Chức năng. Những điều này xác định hành vi của ghế. Ví dụ: nếu chiếc ghế có _________9 được đặt thành true thì nó có thể sử dụng hàm _______18_______0. Bạn có thể thấy rằng tất cả các hàm được khai báo trong lớp
    class Pen {
        constructor(name, color, price){
            this.name = name;
            this.color = color; 
            this.price = price;
        }
        
        showPrice(){
            console.log(`Price of ${this.name} is ${this.price}`);
        }
    }
    
    const pen1 = new Pen("Marker", "Blue", "$3");
    pen1.showPrice();
    7. Đây là những chức năng trừu tượng. Chúng ta sẽ nói nhiều hơn về các chức năng này sau trong bài viết này

Ở cuối đoạn mã, chúng tôi có hai câu lệnh nhật ký giao diện điều khiển. Cái đầu tiên sẽ in ra định nghĩa của lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7. Đối tượng thứ hai sẽ in phiên bản
class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = backSupport;
        this.headSupport = headSupport;
        this.padding = padding;
        this.armRests = armRests;
        this.seatSize = seatSize;
        this.isHeightAdjustable = isHeightAdjustable;
        this.isMovable = isMovable;
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);

console.dir("Chair Prototype", Chair);
console.log("Chair Object", newChair);
3

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
bảng điều khiển đầu tiên. đầu ra dir

Nếu bạn nhìn vào đầu ra đầu tiên, nó sẽ in ra lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7. Chúng ta hãy xem nội dung của nó

  • Nó bao gồm một tài sản
    class Chair {
        constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
            this.color = color;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.backSupport = backSupport;
            this.headSupport = headSupport;
            this.padding = padding;
            this.armRests = armRests;
            this.seatSize = seatSize;
            this.isHeightAdjustable = isHeightAdjustable;
            this.isMovable = isMovable;
        }
        
        adjustableHeight() {};
        adjustAngle(){};
        moveChair(){};    
    }
    
    const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);
    
    console.dir("Chair Prototype", Chair);
    console.log("Chair Object", newChair);
    5. Đây là nguyên mẫu mà tất cả các thể hiện của lớp Ghế sẽ có
  • Thuộc tính
    class Chair {
        constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
            this.color = color;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.backSupport = backSupport;
            this.headSupport = headSupport;
            this.padding = padding;
            this.armRests = armRests;
            this.seatSize = seatSize;
            this.isHeightAdjustable = isHeightAdjustable;
            this.isMovable = isMovable;
        }
        
        adjustableHeight() {};
        adjustAngle(){};
        moveChair(){};    
    }
    
    const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);
    
    console.dir("Chair Prototype", Chair);
    console.log("Chair Object", newChair);
    6 là tên của đối tượng
  • Cuối cùng, chúng ta có thuộc tính
    class Chair {
        constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
            this.color = color;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.backSupport = backSupport;
            this.headSupport = headSupport;
            this.padding = padding;
            this.armRests = armRests;
            this.seatSize = seatSize;
            this.isHeightAdjustable = isHeightAdjustable;
            this.isMovable = isMovable;
        }
        
        adjustableHeight() {};
        adjustAngle(){};
        moveChair(){};    
    }
    
    const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);
    
    console.dir("Chair Prototype", Chair);
    console.log("Chair Object", newChair);
    7  hoặc
    class Chair {
        constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
            this.color = color;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.backSupport = backSupport;
            this.headSupport = headSupport;
            this.padding = padding;
            this.armRests = armRests;
            this.seatSize = seatSize;
            this.isHeightAdjustable = isHeightAdjustable;
            this.isMovable = isMovable;
        }
        
        adjustableHeight() {};
        adjustAngle(){};
        moveChair(){};    
    }
    
    const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);
    
    console.dir("Chair Prototype", Chair);
    console.log("Chair Object", newChair);
    8. Đây là nguyên mẫu thực tế của lớp
    class Pen {
        constructor(name, color, price){
            this.name = name;
            this.color = color; 
            this.price = price;
        }
        
        showPrice(){
            console.log(`Price of ${this.name} is ${this.price}`);
        }
    }
    
    const pen1 = new Pen("Marker", "Blue", "$3");
    pen1.showPrice();
    7
{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
Đầu ra nhật ký bảng điều khiển thứ hai

Câu lệnh nhật ký thứ hai in ra thông tin của đối tượng ghế. Nó sẽ bao gồm tất cả các thuộc tính của lớp Chair. Nếu để ý kỹ, bạn có thể thấy nguyên mẫu của trường hợp này tương tự như nguyên mẫu của thuộc tính

class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = backSupport;
        this.headSupport = headSupport;
        this.padding = padding;
        this.armRests = armRests;
        this.seatSize = seatSize;
        this.isHeightAdjustable = isHeightAdjustable;
        this.isMovable = isMovable;
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);

console.dir("Chair Prototype", Chair);
console.log("Chair Object", newChair);
5 của lớp ghế. Điều này xảy ra do kế thừa nguyên mẫu

Bây giờ, hãy xem cách chúng ta có thể sử dụng khái niệm này bằng cách thêm một thành phần/lớp mới vào Hệ thống quản lý ghế của chúng ta

Chức năng trừu tượng và tính kế thừa trong hệ thống quản lý ghế

Hàm trừu tượng chỉ là một chữ ký hàm trong một lớp mà không có bất kỳ triển khai nào. Nó giúp chúng tôi tổng quát hóa mã để các lớp con có thể sử dụng chúng và thêm phần triển khai của riêng chúng vào đó

Để chứng minh điều này trong trường hợp sử dụng của chúng tôi, hãy thêm một thành phần nữa vào Hệ thống quản lý ghế của chúng tôi

Tôi đã sửa đổi lớp ghế để bây giờ nó bao gồm các giá trị mặc định. Các giá trị mặc định này sẽ được sử dụng bởi tất cả các phiên bản. Sau này lớp con có thể sửa đổi nó. Chúng ta sẽ thấy ngay làm thế nào chúng ta có thể đạt được điều này. Hãy xem lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 mới bên dưới

class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = true;
        this.headSupport = false;
        this.padding = "3 inch";
        this.armRests = true;
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair();

newChair;
Lớp chủ tịch với giá trị mặc định

Bây giờ, hãy thêm một thành phần/lớp mới có tên là

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2. Điều này sẽ kế thừa các thuộc tính và phương thức từ lớp
class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7. Sơ đồ lớp sửa đổi mới sẽ trông như thế này

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
sơ đồ lớp

Lưu ý rằng lớp mới

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2 chỉ bao gồm các phương thức chứ không phải các thuộc tính. Ở đây chúng ta giả định rằng tất cả các thuộc tính sẽ được kế thừa từ lớp
class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7.  

Đối với lớp

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2, chúng tôi đã triển khai các phương thức trừu tượng có trong lớp
class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7

Hãy xem đoạn mã dưới đây cho lớp

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2

class OfficeChair extends Chair{
    constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
        super();
        this.type = "Office Chair";
        this.color = color;
        this.isHeightAdjustable = isHeightAdjustable;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.isMovable = true;
    }
    
    adjustableHeight(height){
        if(height > this.seatHeight){
            console.log(`Chair height changed to ${height}`);        
        } else {
            console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
        }
    }
    
    adjustAngle(angle){
        if(angle >= this.recliningAngle){
            console.log(`Chair angle changed to ${angle}`);        
        } else {
            console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
        }
    }
    
    moveChair(x,y){
        console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
    }
}

const newOfficeChair = new OfficeChair("Red", true, 30, 30);

console.log(newOfficeChair.adjustableHeight(31));
console.log(newOfficeChair.adjustAngle(40));
console.log(newOfficeChair.moveChair(10,20));
Triển khai lớp OfficeChair

Đây là lớp kế thừa các chức năng và thuộc tính từ lớp cha

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
9. Nó sử dụng từ khóa
class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = true;
        this.headSupport = false;
        this.padding = "3 inch";
        this.armRests = true;
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair();

newChair;
0 để cho phép lớp
{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2 thực hiện kế thừa

Từ khóa

class Chair {
    constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.backSupport = true;
        this.headSupport = false;
        this.padding = "3 inch";
        this.armRests = true;
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

const newChair = new Chair();

newChair;
0 có cú pháp như sau

class ChildClass extends ParentClass{...}

Tiếp theo, chúng ta có hàm tạo và triển khai một số hàm từ lớp cha. Lưu ý rằng chúng tôi đang sử dụng từ khóa

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
4 trong hàm tạo

Chúng ta sử dụng từ khóa

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
4 để gọi phương thức khởi tạo của lớp cha. Chúng ta cũng có thể sử dụng nó để gọi các hàm và thuộc tính của lớp cha

Một lời cảnh báo khi bạn đang sử dụng từ khóa

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
4

  • Đảm bảo rằng bạn gọi hàm
    function Pen(name, color, price) {
        this.name = name;
        this.color = color;
        this.price = price;
    }
    
    const pen1 = new Pen("Marker", "Blue", "$3");
    
    Pen.prototype.showPrice = function(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
    
    pen1.showPrice();
    4 khi bắt đầu hàm tạo. Nếu không, và bạn cố gắng truy cập các thuộc tính của lớp cha trước khi bạn sử dụng
    function Pen(name, color, price) {
        this.name = name;
        this.color = color;
        this.price = price;
    }
    
    const pen1 = new Pen("Marker", "Blue", "$3");
    
    Pen.prototype.showPrice = function(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
    
    pen1.showPrice();
    4 trong hàm tạo của lớp con, nó sẽ báo lỗi
  • Khi hàm
    function Pen(name, color, price) {
        this.name = name;
        this.color = color;
        this.price = price;
    }
    
    const pen1 = new Pen("Marker", "Blue", "$3");
    
    Pen.prototype.showPrice = function(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
    
    pen1.showPrice();
    4 được gọi, thì bạn có thể truy cập tất cả các thuộc tính và hàm của lớp cha
  • Super không chỉ liên quan đến các lớp – bạn cũng có thể sử dụng nó để gọi các hàm trên cha của đối tượng

Bạn có thể đọc thêm về

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
4 trong tài liệu MDN

Cuối cùng, nếu bạn để ý, chúng tôi đã thêm phần triển khai cho các hàm trừu tượng. Các chức năng như sau

  • class Chair {
        constructor(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
            this.color = color;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.backSupport = backSupport;
            this.headSupport = headSupport;
            this.padding = padding;
            this.armRests = armRests;
            this.seatSize = seatSize;
            this.isHeightAdjustable = isHeightAdjustable;
            this.isMovable = isMovable;
        }
        
        adjustableHeight() {};
        adjustAngle(){};
        moveChair(){};    
    }
    
    const newChair = new Chair("Blue","25 inch","20 deg",true,false,"3 inch",true,"16 inch",false,false);
    
    console.dir("Chair Prototype", Chair);
    console.log("Chair Object", newChair);
    0. Hàm này sẽ kiểm tra xem chiều cao nhập vào có lớn hơn chiều cao tối thiểu của ghế không. Nếu có, chúng tôi có thể thay đổi chiều cao nếu không sẽ hiển thị thông báo lỗi. Người ngồi cũng có thể tăng giảm chiều cao của ghế. Lưu ý rằng
    class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    1 là chiều cao tối thiểu của ghế tính từ mặt đất bên dưới mà người đó không thể hạ thấp chiều cao
  • class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    2. Chức năng này sẽ kiểm tra xem góc đầu vào có lớn hơn giá trị mặc định
    class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    3. Nếu góc đầu vào lớn hơn góc mặc định thì góc sẽ thay đổi nếu không sẽ hiển thị thông báo lỗi
  • class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    4. Bất kỳ ghế nào có thuộc tính
    class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    5 là true thì lớp tương ứng sẽ triển khai hàm
    class OfficeChair extends Chair{
        constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
            super();
            this.type = "Office Chair";
            this.color = color;
            this.isHeightAdjustable = isHeightAdjustable;
            this.seatHeight = seatHeight;
            this.recliningAngle = recliningAngle;
            this.isMovable = true;
        }
        
        adjustableHeight(height){
            if(height > this.seatHeight){
                console.log(`Chair height changed to ${height}`);        
            } else {
                console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
            }
        }
        
        adjustAngle(angle){
            if(angle >= this.recliningAngle){
                console.log(`Chair angle changed to ${angle}`);        
            } else {
                console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
            }
        }
        
        moveChair(x,y){
            console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
        }
    }
    
    const newOfficeChair = new OfficeChair("Red", true, 30, 30);
    
    console.log(newOfficeChair.adjustableHeight(31));
    console.log(newOfficeChair.adjustAngle(40));
    console.log(newOfficeChair.moveChair(10,20));
    4. Nó chỉ đơn giản là giúp di chuyển ghế dựa trên tọa độ x và y đầu vào

Lưu ý rằng chúng tôi cũng đã khởi tạo lại một số thuộc tính của lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7, chẳng hạn như
class OfficeChair extends Chair{
    constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
        super();
        this.type = "Office Chair";
        this.color = color;
        this.isHeightAdjustable = isHeightAdjustable;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.isMovable = true;
    }
    
    adjustableHeight(height){
        if(height > this.seatHeight){
            console.log(`Chair height changed to ${height}`);        
        } else {
            console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
        }
    }
    
    adjustAngle(angle){
        if(angle >= this.recliningAngle){
            console.log(`Chair angle changed to ${angle}`);        
        } else {
            console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
        }
    }
    
    moveChair(x,y){
        console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
    }
}

const newOfficeChair = new OfficeChair("Red", true, 30, 30);

console.log(newOfficeChair.adjustableHeight(31));
console.log(newOfficeChair.adjustAngle(40));
console.log(newOfficeChair.moveChair(10,20));
8. Chúng tôi sẽ xác định rõ ràng thuộc tính
class OfficeChair extends Chair{
    constructor(color, isHeightAdjustable, seatHeight, recliningAngle){
        super();
        this.type = "Office Chair";
        this.color = color;
        this.isHeightAdjustable = isHeightAdjustable;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.isMovable = true;
    }
    
    adjustableHeight(height){
        if(height > this.seatHeight){
            console.log(`Chair height changed to ${height}`);        
        } else {
            console.log(`Height cannot be decreased more than the seat height ${this.seatHeight}`);
        }
    }
    
    adjustAngle(angle){
        if(angle >= this.recliningAngle){
            console.log(`Chair angle changed to ${angle}`);        
        } else {
            console.log(`Angle cannot be decreased more than the min reclining angle ${this.recliningAngle}`);
        }
    }
    
    moveChair(x,y){
        console.log(`Chair moved to co-ordinates = (${x}, ${y})`);
    }
}

const newOfficeChair = new OfficeChair("Red", true, 30, 30);

console.log(newOfficeChair.adjustableHeight(31));
console.log(newOfficeChair.adjustAngle(40));
console.log(newOfficeChair.moveChair(10,20));
8 cho mỗi phân lớp. Điều này sẽ giúp chúng tôi phân loại những chiếc ghế có trong kho bằng cách chỉ định các lớp này cho từng chiếc

Bây giờ bạn sẽ có một ý tưởng về các hàm trừu tượng là gì và chúng có thể hữu ích như thế nào. Một số lợi thế của việc có chức năng trừu tượng

  • Giảm sự dư thừa trong codebase
  • Cung cấp một cách thích hợp để tổng quát hóa các lớp
  • Cho phép các lớp con linh hoạt thực hiện bất kỳ chức năng trừu tượng nào mà chúng cần

Từ khóa tĩnh trong Javascript

Từ khóa

class ChildClass extends ParentClass{...}
0 trong JavaScript giúp bạn định nghĩa các hàm và thuộc tính trong lớp mà thể hiện của đối tượng không thể gọi được. Chúng chỉ có thể được gọi bởi chính lớp bao gồm các hàm và thuộc tính tĩnh này

Nói chung, chúng tôi sử dụng các phương thức

class ChildClass extends ParentClass{...}
0 trong các lớp cho các mục đích hữu ích như in ra tất cả các thuộc tính của lớp, tạo một đối tượng mới, xóa các đối tượng khác của lớp, v.v.  

Ưu điểm của việc sử dụng các hàm hoặc thuộc tính của

class ChildClass extends ParentClass{...}
0 trong một lớp là

  • Chúng có thể được sử dụng để tạo các hàm/thuộc tính không cần có trong các thể hiện. Điều này giúp duy trì một số sự cô lập trong codebase
  • Chúng giảm dư thừa mã trong một số trường hợp

Bây giờ hãy xem cách chúng ta có thể triển khai khái niệm này trong lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 của chúng ta. Chúng tôi cũng sẽ xem xét một số trường hợp sử dụng mà chúng tôi có thể sử dụng từ khóa
class ChildClass extends ParentClass{...}
0

Dưới đây là các tình huống mà bạn có thể sử dụng từ khóa

class ChildClass extends ParentClass{...}
0

  • Sử dụng trong các lớp học
  • Tĩnh trong tĩnh
  • Gọi tĩnh từ một hàm tạo
  • Khối khởi tạo tĩnh lớp

Để biết thêm thông tin về các tình huống trên, vui lòng truy cập tài liệu MDN

Chúng ta sẽ xem tất cả các biến thể của lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 thông qua các tình huống này

Cách sử dụng từ khóa class ChildClass extends ParentClass{...}0 trong lớp học

Giống như bất kỳ ngôn ngữ lập trình nào khác, đây là một trong những cách thân thiện với người mới bắt đầu nhất để sử dụng từ khóa tĩnh. Hãy định nghĩa một số phương thức và thuộc tính của các lớp như

class ChildClass extends ParentClass{...}
0 và quan sát hành vi

Hãy nhìn vào đoạn mã dưới đây

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

Dưới đây là đầu ra của mã trên

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Biến tĩnh
Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Đầu ra của hàm tĩnh

Như bạn có thể thấy ở trên, các phương thức tĩnh chỉ có thể truy cập thông qua chính lớp đó. Nó không thể được truy cập bởi các thể hiện của lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7. Các thể hiện của lớp không có các thuộc tính tĩnh

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Không có thành viên tĩnh trong trường hợp

Như bạn có thể thấy ở trên, thể hiện

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
0 của lớp
class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 không có phương thức hoặc thuộc tính tĩnh có trong định nghĩa của nó

Nếu bạn cố gắng truy cập một phương thức tĩnh hoặc một thuộc tính bằng cách sử dụng một thể hiện của lớp thì nó sẽ đưa ra lỗi tham chiếu hoặc đơn giản là trả về không xác định

Cách sử dụng từ khóa class ChildClass extends ParentClass{...}0 trong một hàm tĩnh khác

Có thể xảy ra trường hợp bạn cần sử dụng các thuộc tính hoặc hàm tĩnh bên trong một hàm tĩnh khác. Bạn có thể làm điều này bằng cách tham khảo thuộc tính/hàm khác của mình bằng cách sử dụng từ khóa này bên trong hàm tĩnh

Hãy sửa đổi lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7 của chúng ta để cho thấy nó hoạt động như thế nào

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }

		//Static within static usage
		static printDefaultProps(){
				console.log(`Chair Back Support = ${this.backSupport}`);
				console.log(`Arm rests support = ${this.armRests}`);
		}
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
Tĩnh trong triển khai tĩnh
Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Đầu ra của đoạn mã trên

Như bạn có thể thấy hàm

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
4 có quyền truy cập vào các thuộc tính tĩnh
class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
5 và
class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
6

Cách gọi các thuộc tính/hàm tĩnh từ một hàm tạo

Tương tự như những gì chúng ta đã thấy ở trên, bạn cũng có thể truy cập các thuộc tính/hàm tĩnh này trong hàm tạo. Để làm điều này, mọi thứ ở đây hơi khác một chút

Trong một hàm tạo để gọi một thuộc tính/hàm tĩnh, bạn cần sử dụng

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
7 hoặc
class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
8. Điều này xảy ra vì từ khóa
class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
9 không có quyền truy cập trực tiếp vào các thành viên tĩnh. Điều này không chỉ đúng với hàm tạo mà bất kỳ hàm không tĩnh nào

Hãy cố gắng hiểu điều này bằng cách sửa đổi lớp

class Pen {
    constructor(name, color, price){
        this.name = name;
        this.color = color; 
        this.price = price;
    }
    
    showPrice(){
        console.log(`Price of ${this.name} is ${this.price}`);
    }
}

const pen1 = new Pen("Marker", "Blue", "$3");
pen1.showPrice();
7

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
0

Trong đoạn mã trên, dòng cuối cùng

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }

		//Static within static usage
		static printDefaultProps(){
				console.log(`Chair Back Support = ${this.backSupport}`);
				console.log(`Arm rests support = ${this.armRests}`);
		}
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
1 giới thiệu cách chúng ta có thể sử dụng một phương thức tĩnh bên trong một hàm tạo

Các thành viên riêng của các lớp trong Javascript

Thành viên riêng là thành viên của lớp chỉ có thể được sử dụng nội bộ bởi chính lớp đó. Chúng không thể được truy cập bên ngoài lớp. Ngay cả các thể hiện của lớp cũng không thể truy cập các thành viên riêng tư này

Tất cả các thành viên private được khai báo sử dụng cú pháp

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }

		//Static within static usage
		static printDefaultProps(){
				console.log(`Chair Back Support = ${this.backSupport}`);
				console.log(`Arm rests support = ${this.armRests}`);
		}
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
2. Chúng thường được gọi là tên băm

Hãy xem một ví dụ dựa trên trường hợp sử dụng của chúng tôi

Chúng ta sẽ định nghĩa một số thuộc tính mới bên trong lớp

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2. Giả sử chúng tôi muốn thêm thông tin thanh toán mặc định cho tất cả các ghế văn phòng. Chúng tôi cũng muốn những biến này chỉ có thể truy cập được đối với lớp
{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2 để các hàm tiện ích khác có thể sử dụng các biến này

Chúng tôi không muốn các lớp khác can thiệp vào thông tin thanh toán của các lớp khác. Để xử lý việc này, chúng ta có thể sử dụng các trường riêng tư

Xem xét việc bổ sung các trường sau

  • Giá bán
  • Giảm giá tối đa
  • Địa chỉ người bán
Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Sơ đồ lớp cập nhật

Lưu ý rằng chúng ta có thể biểu diễn các trường riêng tư trong sơ đồ lớp bằng dấu gạch ngang, như thế này.

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }

		//Static within static usage
		static printDefaultProps(){
				console.log(`Chair Back Support = ${this.backSupport}`);
				console.log(`Arm rests support = ${this.armRests}`);
		}
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
5

Hãy xem mã bên dưới để minh họa cách chúng tôi đã thêm các trường này vào lớp

{
    "color": "Blue",
    "seatHeight": "25 inch",
    "recliningAngle": "20 deg",
    "backSupport": true,
    "headSupport": false,
    "padding": "3 inch",
    "armRests": true,
    "seatSize": "16 inch",
    "isHeightAdjustable": false,
    "isMovable": false,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
2

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
1Sử dụng thành viên riêng tư

Khi bạn chạy đoạn mã trên trong bảng điều khiển, bạn sẽ thấy đầu ra sau

Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Đầu ra của các thành viên tư nhân

Như bạn có thể thấy từ đầu ra ở trên, chúng tôi đã thực hiện chức năng

class Chair {
//Defaults that will be common for all the instances:
    static backSupport = true;
    static armRests = true;
    
    constructor(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        //Defaults which can be changed by the subclass class.
        this.color = color;
        this.seatHeight = seatHeight;
        this.recliningAngle = recliningAngle;
        this.headSupport = false;
        this.padding = "3 inch";
        this.seatSize = "16 inch";
        this.isHeightAdjustable = false;
        this.isMovable = false;
        this.type = "Chair";
    } 
        
    static logObjectProps(){
        console.dir(this);
    }

		//Static within static usage
		static printDefaultProps(){
				console.log(`Chair Back Support = ${this.backSupport}`);
				console.log(`Arm rests support = ${this.armRests}`);
		}
    
    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
7. Hàm này truy cập các trường riêng và hàm trong lớp để tạo thông tin thanh toán

Các biến riêng tư này sẽ chỉ có thể truy cập được trong chính lớp đó. Nếu bạn cố gắng tham chiếu bất kỳ thành viên riêng tư nào của lớp thì nó sẽ đưa ra lỗi cú pháp như bên dưới

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
2

Hãy để tôi chứng minh nó trông như thế nào nếu một lớp con cố gắng truy cập các biến riêng tư của lớp cơ sở

function Pen(name, color, price) {
    this.name = name;
    this.color = color;
    this.price = price;
}

const pen1 = new Pen("Marker", "Blue", "$3");

Pen.prototype.showPrice = function(){
    console.log(`Price of ${this.name} is ${this.price}`);
}

pen1.showPrice();
3

Đoạn mã trên sẽ đưa ra một lỗi cú pháp vì bạn đang cố truy cập vào thuộc tính riêng của một lớp khác

Các biến riêng tĩnh nằm ngoài phạm vi của bài đăng trên blog này, vì vậy chúng tôi sẽ không thảo luận thêm về chúng. Nhưng bạn có thể đọc về chúng ở đây

Tóm lược

Đây là một số cách chúng ta có thể tận dụng các lớp trong JavaScript để triển khai các khái niệm lập trình hướng đối tượng trong một ví dụ thực tế

Bạn có thể đọc thêm về các khái niệm hướng đối tượng nâng cao bên dưới

  • đa hình
  • Các loại thừa kế

Cảm ơn bạn đã đọc

Theo dõi tôi trên Twitter, GitHub và LinkedIn

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO

QUẢNG CÁO


Tôi có nên sử dụng lớp hoặc đối tượng JavaScript không?
Keyur Paralkar

Nhà phát triển front-end👨‍💻;


Nếu bạn đọc đến đây, hãy tweet cho tác giả để cho họ thấy bạn quan tâm. Tweet một lời cảm ơn

Học cách viết mã miễn phí. Chương trình giảng dạy mã nguồn mở của freeCodeCamp đã giúp hơn 40.000 người có được việc làm với tư cách là nhà phát triển. Bắt đầu

Bạn vẫn nên sử dụng các lớp trong JavaScript chứ?

Trong JavaScript, bạn không . Bạn có thể viết bất kỳ chương trình nào bạn muốn mà không cần sử dụng các lớp hoặc từ khóa this. Thật vậy, cú pháp lớp hơi mới đối với JavaScript và mã hướng đối tượng đã được viết trước với các hàm. Cú pháp lớp chỉ là đường cú pháp đối với cách tiếp cận dựa trên chức năng đối với OOP.

Khi nào tôi nên sử dụng các lớp trong JavaScript?

Các lớp cung cấp một phương tiện được cải thiện để tạo các mẫu đối tượng, thay thế phương pháp sử dụng hàm tạo trước đây. Thông thường, chúng tôi được yêu cầu viết mã cho nhiều đối tượng có một số thuộc tính chung

Tại sao sử dụng lớp trên đối tượng?

Các lớp được yêu cầu trong OOP bởi vì. Nó cung cấp khuôn mẫu để tạo đối tượng, có thể liên kết mã vào dữ liệu . Nó có định nghĩa về phương pháp và dữ liệu. Nó hỗ trợ thuộc tính kế thừa của Lập trình hướng đối tượng và do đó có thể duy trì hệ thống phân cấp lớp.

Bạn có nên sử dụng các đối tượng trong JavaScript không?

Sử dụng các đối tượng thật tuyệt vì bạn có thể thêm các phương thức . Phương thức là các chức năng được liên kết với dữ liệu trong đối tượng của bạn. Điều này giúp làm việc với các đối tượng dễ dàng hơn nhiều.