Hướng dẫn how do you call a constructor in javascript? - làm thế nào để bạn gọi một hàm tạo trong javascript?

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

Làm thế nào để bạn gọi một hàm tạo?

Gọi một hàm tạo từ một phương thức không, bạn không thể gọi một hàm tạo từ một phương thức. Nơi duy nhất mà bạn có thể gọi các nhà xây dựng bằng cách sử dụng này (), hoặc, Super Super () là dòng đầu tiên của một hàm tạo khác. Nếu bạn cố gắng gọi các nhà xây dựng rõ ràng ở nơi khác, một lỗi thời gian biên dịch sẽ được tạo ra.The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor. If you try to invoke constructors explicitly elsewhere, a compile time error will be generated.

Tôi có thể gọi phương thức trong trình xây dựng JavaScript không?

Có, có thể, khi hàm hàm tạo của bạn thực thi, giá trị này đã có thuộc tính bên trong [[nguyên mẫu]] trỏ đến các trường hợp ValidateFields., when your constructor function executes, the this value has already the [[Prototype]] internal property pointing to the ValidateFields.

Làm thế nào bạn có thể khai báo một lớp với một hàm tạo trong JavaScript?

Các phương thức lớp được tạo với cùng một cú pháp với các phương thức đối tượng.Sử dụng lớp từ khóa để tạo lớpSau đó thêm bất kỳ số lượng phương thức.Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods.

Bạn có cần một hàm tạo trong JavaScript không?

Bạn có thể xác định một lớp mà không có hàm tạo trong JavaScript.Nếu bạn không chỉ định phương thức Constructor, hàm tạo mặc định sẽ được sử dụng.Theo mặc định, hàm tạo được định nghĩa là: phần thân của một lớp là phần nằm trong dấu ngoặc xoăn {}.Đây là nơi bạn xác định các thành viên lớp, chẳng hạn như phương thức hoặc nhà xây dựng.. If you do not specify a constructor method a default constructor is used. By default, the constructor is defined as: The body of a class is the part that is in curly brackets {} . This is where you define class members, such as methods or constructors.