Hướng dẫn what is static method in class in javascript? - Phương thức tĩnh trong lớp trong javascript là gì?

Phương pháp lớp tĩnh được xác định trên chính lớp.

Bạn không thể gọi phương thức static trên một đối tượng, chỉ trên một lớp đối tượng.

Thí dụ

Lớp xe {& nbsp; trình xây dựng (tên) {& nbsp; & nbsp; & nbsp; this.name = name; & nbsp; } & nbsp; hello () {& nbsp; & nbsp; & nbsp; trả lại "Xin chào !!"; & nbsp; }}
  constructor(name) {
    this.name = name;
  }
  static hello() {
    return "Hello!!";
  }
}

Hãy để mycar = xe mới ("ford");

// Bạn có thể gọi 'Hello ()' trên lớp xe: document.getEuityById ("demo"). InnerHtml = car.hello ();
document.getElementById("demo").innerHTML = Car.hello();

// nhưng không phải trên một đối tượng xe: // document.getEuityById ("demo"). InnerHtml = mycar.hello (); // Điều này sẽ gây ra lỗi.
// document.getElementById("demo").innerHTML = myCar.hello();
// this will raise an error.

Hãy tự mình thử »

Nếu bạn muốn sử dụng đối tượng Mycar bên trong phương thức static, bạn có thể gửi nó dưới dạng tham số:

Thí dụ

Lớp xe {& nbsp; trình xây dựng (tên) {& nbsp; & nbsp; & nbsp; this.name = name; & nbsp; } & nbsp; hello () {& nbsp; & nbsp; & nbsp; trả lại "Xin chào !!"; & nbsp; }}
  constructor(name) {
    this.name = name;
  }
  static hello(x) {
    return "Hello " + x.name;
  }
}
let myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);

Hãy tự mình thử »




Từ khóa static xác định một phương thức hoặc thuộc tính tĩnh cho một lớp hoặc khối khởi tạo tĩnh lớp (xem liên kết để biết thêm thông tin về việc sử dụng này). Cả các phương thức tĩnh và tính chất tĩnh đều không thể được gọi trên các trường hợp của lớp. Thay vào đó, họ được gọi vào chính lớp.static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.

Các phương thức tĩnh thường là các hàm tiện ích, chẳng hạn như các hàm để tạo hoặc sao chép các đối tượng, trong khi các thuộc tính tĩnh rất hữu ích cho bộ nhớ cache, cấu hình cố định hoặc bất kỳ dữ liệu nào khác mà bạn không cần được sao chép trên các trường hợp.

Lưu ý: Trong bối cảnh của các lớp, Nội dung tài liệu web MDN sử dụng các thuộc tính và trường thuật ngữ có thể thay thế cho nhau. In the context of classes, MDN Web Docs content uses the terms properties and fields interchangeably.

Thử nó

Cú pháp

static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}

Ví dụ

Sử dụng các thành viên tĩnh trong các lớp học

Ví dụ sau đây cho thấy một số điều:

  1. Làm thế nào một thành viên tĩnh (phương thức hoặc thuộc tính) được xác định trên một lớp.
  2. Rằng một lớp với một thành viên tĩnh có thể được phân lớp phụ.
  3. Làm thế nào một thành viên tĩnh có thể và không thể được gọi.

class Triple {
  static customName = 'Tripler';
  static description = 'I triple any number you provide';
  static calculate(n = 1) {
    return n * 3;
  }
}

class SquaredTriple extends Triple {
  static longDescription;
  static description = 'I square the triple of any number you provide';
  static calculate(n) {
    return super.calculate(n) * super.calculate(n);
  }
}

console.log(Triple.description);            // 'I triple any number you provide'
console.log(Triple.calculate());            // 3
console.log(Triple.calculate(6));           // 18

const tp = new Triple();

console.log(SquaredTriple.calculate(3));    // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description);     // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName);      // 'Tripler'

// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate());                // 'tp.calculate is not a function'

Gọi các thành viên tĩnh từ một phương thức tĩnh khác

Để gọi một phương thức hoặc thuộc tính tĩnh trong một phương thức tĩnh khác của cùng một lớp, bạn có thể sử dụng từ khóa this.

class StaticMethodCall {
  static staticProperty = 'static property';
  static staticMethod() {
    return `Static method and ${this.staticProperty} has been called`;
  }
  static anotherStaticMethod() {
    return `${this.staticMethod()} from another static method`;
  }
}
StaticMethodCall.staticMethod();
// 'Static method and static property has been called'

StaticMethodCall.anotherStaticMethod();
// 'Static method and static property has been called from another static method'

Gọi các thành viên tĩnh từ một hàm tạo lớp và các phương thức khác

Các thành viên tĩnh không thể truy cập trực tiếp bằng cách sử dụng từ khóa this từ các phương thức không tĩnh. Bạn cần gọi cho họ bằng tên lớp: CLASSNAME.STATIC_METHOD_NAME() /

class Triple {
  static customName = 'Tripler';
  static description = 'I triple any number you provide';
  static calculate(n = 1) {
    return n * 3;
  }
}

class SquaredTriple extends Triple {
  static longDescription;
  static description = 'I square the triple of any number you provide';
  static calculate(n) {
    return super.calculate(n) * super.calculate(n);
  }
}

console.log(Triple.description);            // 'I triple any number you provide'
console.log(Triple.calculate());            // 3
console.log(Triple.calculate(6));           // 18

const tp = new Triple();

console.log(SquaredTriple.calculate(3));    // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description);     // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName);      // 'Tripler'

// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate());                // 'tp.calculate is not a function'
0 hoặc bằng cách gọi phương thức là thuộc tính của
class Triple {
  static customName = 'Tripler';
  static description = 'I triple any number you provide';
  static calculate(n = 1) {
    return n * 3;
  }
}

class SquaredTriple extends Triple {
  static longDescription;
  static description = 'I square the triple of any number you provide';
  static calculate(n) {
    return super.calculate(n) * super.calculate(n);
  }
}

console.log(Triple.description);            // 'I triple any number you provide'
console.log(Triple.calculate());            // 3
console.log(Triple.calculate(6));           // 18

const tp = new Triple();

console.log(SquaredTriple.calculate(3));    // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description);     // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName);      // 'Tripler'

// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate());                // 'tp.calculate is not a function'
1:
class Triple {
  static customName = 'Tripler';
  static description = 'I triple any number you provide';
  static calculate(n = 1) {
    return n * 3;
  }
}

class SquaredTriple extends Triple {
  static longDescription;
  static description = 'I square the triple of any number you provide';
  static calculate(n) {
    return super.calculate(n) * super.calculate(n);
  }
}

console.log(Triple.description);            // 'I triple any number you provide'
console.log(Triple.calculate());            // 3
console.log(Triple.calculate(6));           // 18

const tp = new Triple();

console.log(SquaredTriple.calculate(3));    // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description);     // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName);      // 'Tripler'

// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate());                // 'tp.calculate is not a function'
2 /
class Triple {
  static customName = 'Tripler';
  static description = 'I triple any number you provide';
  static calculate(n = 1) {
    return n * 3;
  }
}

class SquaredTriple extends Triple {
  static longDescription;
  static description = 'I square the triple of any number you provide';
  static calculate(n) {
    return super.calculate(n) * super.calculate(n);
  }
}

console.log(Triple.description);            // 'I triple any number you provide'
console.log(Triple.calculate());            // 3
console.log(Triple.calculate(6));           // 18

const tp = new Triple();

console.log(SquaredTriple.calculate(3));    // 81 (not affected by parent's instantiation)
console.log(SquaredTriple.description);     // 'I square the triple of any number you provide'
console.log(SquaredTriple.longDescription); // undefined
console.log(SquaredTriple.customName);      // 'Tripler'

// This throws because calculate() is a static member, not an instance member.
console.log(tp.calculate());                // 'tp.calculate is not a function'
3

class StaticMethodCall {
  constructor() {
    console.log(StaticMethodCall.staticProperty); // 'static property'
    console.log(this.constructor.staticProperty); // 'static property'
    console.log(StaticMethodCall.staticMethod()); // 'static method has been called.'
    console.log(this.constructor.staticMethod()); // 'static method has been called.'
  }

  static staticProperty = 'static property';
  static staticMethod() {
    return 'static method has been called.';
  }
}

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # Sec-Class-Deellitions
# sec-class-definitions

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

Phương pháp tĩnh trong một lớp là gì?

Phương pháp tĩnh trong Java là một phương pháp là một phần của lớp chứ không phải là một thể hiện của lớp đó. Mỗi phiên bản của một lớp đều có quyền truy cập vào phương thức. Các phương thức tĩnh có quyền truy cập vào các biến lớp (biến tĩnh) mà không cần sử dụng đối tượng (trường hợp) của lớp. Chỉ dữ liệu tĩnh có thể được truy cập bằng phương pháp tĩnh.a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance). Only static data may be accessed by a static method.

Các phương pháp tĩnh được gọi trên JavaScript là gì?

Phương pháp tĩnh JavaScript JavaScript cung cấp các phương thức tĩnh thuộc về lớp thay vì một thể hiện của lớp đó. Vì vậy, một thể hiện không bắt buộc phải gọi phương thức tĩnh. Các phương pháp này được gọi trực tiếp trên chính lớp.directly on the class itself.

Phương pháp tĩnh là gì?

Phương thức tĩnh (hoặc hàm tĩnh) là một phương thức được xác định là thành viên của một đối tượng nhưng có thể truy cập trực tiếp từ hàm tạo của đối tượng API, thay vì từ một thể hiện đối tượng được tạo thông qua hàm tạo.a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

Phương pháp tĩnh trong ES6 là gì?

Như MDN mô tả, các phương thức tĩnh được gọi mà không cần khởi tạo lớp của họ và cũng không thể gọi được khi lớp được khởi tạo.Các phương thức tĩnh thường được sử dụng để tạo các chức năng tiện ích cho một ứng dụng.Nói cách khác, các phương thức tĩnh không có quyền truy cập vào dữ liệu được lưu trữ trong các đối tượng cụ thể.Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.” In other words, static methods have no access to data stored in specific objects.