Hướng dẫn what is constructor in javascript es6? - hàm tạo trong javascript es6 là gì?

Phương pháp

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 là một phương pháp đặc biệt của một lớp để tạo và khởi tạo một thể hiện đối tượng của lớp đó.
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1
method is a special method of a class for creating and initializing an object instance of that class.

Lưu ý: Trang này giới thiệu cú pháp

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1. Đối với thuộc tính
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 có trên tất cả các đối tượng, xem
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
4.
This page introduces the
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 syntax. For the
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 property present on all objects, see
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
4.

Thử nó

Cú pháp

constructor() { /* … */ }
constructor(argument0) { /* … */ }
constructor(argument0, argument1) { /* … */ }
constructor(argument0, argument1, /* … ,*/ argumentN) { /* … */ }

Sự mô tả

Hàm tạo cho phép bạn cung cấp bất kỳ khởi tạo tùy chỉnh nào phải được thực hiện trước khi bất kỳ phương thức nào khác có thể được gọi trên một đối tượng khởi tạo.

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto

Nếu bạn không cung cấp hàm tạo riêng của mình, thì hàm tạo mặc định sẽ được cung cấp cho bạn. Nếu lớp của bạn là lớp cơ sở, hàm tạo mặc định trống:

Nếu lớp của bạn là một lớp có nguồn gốc, hàm tạo mặc định gọi hàm tạo cha mẹ, việc chuyển qua bất kỳ đối số nào được cung cấp:

constructor(...args) {
  super(...args);
}

LƯU Ý: Sự khác biệt giữa một hàm tạo rõ ràng như ở trên và hàm tạo mặc định là cái sau không thực sự gọi trình lặp lại mảng thông qua việc lan truyền đối số. The difference between an explicit constructor like the one above and the default constructor is that the latter doesn't actually invoke the array iterator through argument spreading.

Điều đó cho phép mã như thế này hoạt động:

class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}

Lớp

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
5 không cần một hàm tạo rõ ràng, bởi vì nó không cần phải thực hiện bất kỳ khởi tạo tùy chỉnh nào. Hàm xây dựng mặc định sau đó chăm sóc khởi tạo cha mẹ
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
6 từ đối số mà nó được đưa ra.

Tuy nhiên, nếu bạn cung cấp hàm tạo của riêng mình và lớp của bạn xuất phát từ một số lớp cha, thì bạn phải gọi rõ ràng hàm tạo lớp cha mẹ bằng cách sử dụng

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
7. Ví dụ:

class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}

Sử dụng

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
8 trên một lớp trải qua các bước sau:

  1. . Phần này không nên truy cập
    constructor(...args) {
      super(...args);
    }
    
    1 vì nó chưa được khởi tạo.
  2. .
  3. Các trường của lớp hiện tại được khởi tạo.
  4. Cơ thể
    class Person {
      constructor(name) {
        this.name = name;
      }
    
      introduce() {
        console.log(`Hello, my name is ${this.name}`);
      }
    }
    
    const otto = new Person("Otto");
    
    otto.introduce(); // Hello, my name is Otto
    
    1 sau cuộc gọi
    class Person {
      constructor(name) {
        this.name = name;
      }
    
      introduce() {
        console.log(`Hello, my name is ${this.name}`);
      }
    }
    
    const otto = new Person("Otto");
    
    otto.introduce(); // Hello, my name is Otto
    
    7 (hoặc toàn bộ cơ thể, nếu đó là lớp cơ sở) được đánh giá.

Trong thân

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1, bạn có thể truy cập đối tượng được tạo thông qua
constructor(...args) {
  super(...args);
}
1 và truy cập lớp được gọi bằng
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
8 đến
constructor(...args) {
  super(...args);
}
8. Lưu ý rằng các phương thức (bao gồm cả getters và setters) và chuỗi nguyên mẫu đã được khởi tạo trên
constructor(...args) {
  super(...args);
}
1 trước khi
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 được thực thi, do đó bạn thậm chí có thể truy cập các phương thức của lớp con từ hàm tạo của siêu lớp. Tuy nhiên, nếu các phương pháp đó sử dụng
constructor(...args) {
  super(...args);
}
1,
constructor(...args) {
  super(...args);
}
1 sẽ chưa được khởi tạo hoàn toàn. Điều này có nghĩa là đọc các trường công khai của lớp dẫn xuất sẽ dẫn đến
class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
3, trong khi đọc các trường riêng sẽ dẫn đến
class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
4.

new (class C extends class B {
  constructor() {
    console.log(this.foo());
  }
} {
  #a = 1;
  foo() {
    return this.#a; // TypeError: Cannot read private member #a from an object whose class did not declare it
    // It's not really because the class didn't declare it,
    // but because the private field isn't initialized yet
    // when the superclass constructor is running
  }
})();

Phương thức

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 có thể có giá trị trả về. Mặc dù lớp cơ sở có thể trả về bất cứ thứ gì từ hàm tạo của nó, lớp dẫn xuất phải trả về một đối tượng hoặc
class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
3 hoặc
class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
4 sẽ bị ném.

class ParentClass {
  constructor() {
    return 1;
  }
}

console.log(new ParentClass()); // ParentClass {}
// The return value is ignored because it's not an object
// This is consistent with function constructors

class ChildClass extends ParentClass {
  constructor() {
    return 1;
  }
}

console.log(new ChildClass()); // TypeError: Derived constructors may only return object or undefined

Nếu hàm tạo lớp cha mẹ trả về một đối tượng, đối tượng đó sẽ được sử dụng làm giá trị

constructor(...args) {
  super(...args);
}
1 trên đó các trường lớp của lớp dẫn xuất sẽ được xác định. Thủ thuật này được gọi là "Quay trở lại", cho phép các trường của lớp có nguồn gốc (bao gồm cả các trường riêng tư) được xác định trên các đối tượng không liên quan.

Chỉ có thể có một phương pháp đặc biệt với tên

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 trong một lớp. Có nhiều hơn một lần xuất hiện của phương thức
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 trong một lớp sẽ gây ra lỗi
class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
1. Có một getter hoặc setter được gọi là
class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 cũng là một
class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
1.

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
1 tuân theo cú pháp phương thức bình thường, vì vậy các giá trị mặc định tham số, tham số REST, v.v. đều có thể được sử dụng.

class Person {
  constructor(name = "Anonymous") {
    this.name = name;
  }
  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person = new Person();
person.introduce(); // Hello, my name is Anonymous

Các hàm tạo phải là một tên theo nghĩa đen. Các thuộc tính được tính toán không thể trở thành hàm tạo.

class Foo {
  // This is a computed property. It will not be picked up as a constructor.
  ["constructor"]() {
    console.log("called");
    this.a = 1;
  }
}

const foo = new Foo(); // No log
console.log(foo); // Foo {}
foo.constructor(); // Logs "called"
console.log(foo); // Foo { a: 1 }

Ví dụ

Sử dụng hàm tạo

Đoạn mã này được lấy từ mẫu lớp (bản demo trực tiếp).

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // NOTE: In derived classes, `super()` must be called before you
    // can use `this`. Leaving this out will cause a ReferenceError.
    this.name = "Square";
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.height = value ** 0.5;
    this.width = value ** 0.5;
  }
}

Gọi Super trong một hàm tạo bị ràng buộc với một nguyên mẫu khác

Ở đây, nguyên mẫu của lớp

class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
5 được thay đổi, nhưng hàm tạo của lớp cơ sở của nó,
class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
6, vẫn được gọi khi một thể hiện mới của một hình vuông được tạo. Để biết thêm thông tin về lý do tại sao, xem tài liệu tham khảo
class ValidationError extends Error {
  constructor(message) {
    super(message); // call parent class constructor
    this.name = "ValidationError";
    this.code = "42";
  }

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log("Unknown error", error);
    throw error;
  }
}
7.

class Person {
  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const otto = new Person("Otto");

otto.introduce(); // Hello, my name is Otto
0

Thông số kỹ thuật

Sự chỉ rõ
Thông số kỹ thuật ngôn ngữ Ecmascript # Sec Static-Semantics-Constructormethod
# sec-static-semantics-constructormethod

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm

Hàm tạo trong ES6 là gì?

Một hàm tạo là một hàm được gọi là mỗi lần một đối tượng được tạo (còn được gọi là khởi tạo). Trình xây dựng người dùng tạo các thuộc tính của đối tượng (this.name, tuổi này, tuổi này. Email) và gán cho chúng giá trị của các tham số được truyền cho nó (tên, tuổi, email).a function that is called each time an object is created (also referred to as instantiated). The User constructor creates the properties of the object (this.name, this. age, this. email) and assigns them the value of the parameters passed to it (name, age, email).

Chất xây dựng trong JavaScript với ví dụ là gì?

Một hàm tạo là một hàm tạo ra một thể hiện của một lớp thường được gọi là một đối tượng trên mạng.Trong JavaScript, một hàm tạo được gọi khi bạn khai báo một đối tượng bằng cách sử dụng từ khóa mới.Mục đích của hàm tạo là tạo một đối tượng và đặt các giá trị nếu có bất kỳ thuộc tính đối tượng nào có.

Là hàm tạo được phép trong định nghĩa lớp ES6?

Một định nghĩa lớp chỉ có thể bao gồm các hàm tạo và chức năng.Các thành phần này được gọi là thành viên dữ liệu của một lớp.Các lớp chứa các hàm tạo phân bổ bộ nhớ cho các đối tượng của một lớp.. These components are together called as the data members of a class. The classes contain constructors that allocates the memory to the objects of a class.

Mục đích của hàm tạo là gì?

Chúng tôi sử dụng các hàm tạo để khởi tạo đối tượng với trạng thái mặc định hoặc trạng thái ban đầu.Các giá trị mặc định cho các nguyên thủy có thể không phải là những gì bạn đang tìm kiếm.Một lý do khác để sử dụng hàm tạo là nó thông báo về các phụ thuộc.