Hướng dẫn can we call static method from non static method javascript? - chúng ta có thể gọi phương thức tĩnh từ javascript không phương thức tĩnh không?

8

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Tôi tò mò vì tôi nhận được lỗi "không xác định không phải là chức năng". Xem xét lớp học sau:

var FlareError = require('../flare_error.js');

class Currency {

  constructor() {
    this._currencyStore = [];
  }

  static store(currency) {
    for (var key in currency) {
      if (currency.hasOwnProperty(key) && currency[key] !== "") {

        if (Object.keys(JSON.parse(currency[key])).length > 0) {
          var currencyObject = JSON.parse(currency[key]);
          this.currencyValidator(currencyObject);

          currencyObject["current_amount"] = 0;

          this._currencyStore.push(currencyObject);
        }
      }
    }
  }

   currencyValidator(currencyJson) {
    if (!currencyJson.hasOwnProperty('name')) {
      FlareError.error('Currency must have a name attribute in the json.');
    }

    if (!currencyJson.hasOwnProperty('description')) {
      FlareError.error('Currency must have a description attribute in the json.');
    }

    if (!currencyJson.hasOwnProperty('icon')) {
      FlareError.error('Currency must have a icon attribute in the json.');
    }
  }

  static getCurrencyStore() {
    return this._currencyStore;
  }

};

module.exports = Currency;

Tái cấu trúc sang một bên, vấn đề nằm trên dòng: this.currencyValidator(currencyObject); Tôi gặp lỗi "Không xác định không phải là một hàm"

Tôi cho rằng điều này là do tôi có một phương pháp tĩnh mà nội bộ gọi là phương thức không tĩnh? Phương pháp không tĩnh đó sẽ phải tĩnh? Và nếu vậy thì khái niệm this.methodName vẫn hoạt động?

Hỏi ngày 27 tháng 10 năm 2015 lúc 15:17Oct 27, 2015 at 15:17

Hướng dẫn can we call static method from non static method javascript? - chúng ta có thể gọi phương thức tĩnh từ javascript không phương thức tĩnh không?

2

Không, một phương thức tĩnh không thể gọi một phương thức phi tĩnh.

Hãy xem xét rằng bạn có đối tượng ab, cả hai trường hợp của Currency.

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

// Class static initialization block
static {

}
0 tồn tại trên hai đối tượng đó. Bây giờ
static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}
1 thuộc về lớp Currency, không phải là một trong những đối tượng đó. Vì vậy, trong
static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}
3, làm thế nào để biết đối tượng nào để gọi
static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}
4 trên? Câu trả lời đơn giản là nó không thể vì vậy nó không thể. Đây là một trong những cạm bẫy của việc sử dụng các phương pháp tĩnh và một trong những lý do khiến mọi người thường thúc giục họ.

Bất kể, bạn có thể vượt qua điều này bằng cách chuyển a vào

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

// Class static initialization block
static {

}
3 và gọi
static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}
7 thay thế.

Đã trả lời ngày 27 tháng 10 năm 2015 lúc 15:23Oct 27, 2015 at 15:23

JoshjoshJosh

8.0093 huy hiệu vàng25 Huy hiệu bạc48 Huy hiệu đồng3 gold badges25 silver badges48 bronze badges

0

Không có ý nghĩa gì khi gọi một chức năng phi tĩnh từ một chức năng tĩnh, trong bất kỳ ngôn ngữ nào. Tĩnh (trong bối cảnh này) có nghĩa là về cơ bản nó nằm ngoài đối tượng, độc lập với tên. Nó không gắn liền với bất kỳ trường hợp nào và do đó không có các trường

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

// Class static initialization block
static {

}
8 hoặc
static methodName() { /* … */ }
static propertyName [= value];

// Class static initialization block
static {

}
9 để gọi các trường không tĩnh (thành viên)).

Đã trả lời ngày 27 tháng 10 năm 2015 lúc 15:20Oct 27, 2015 at 15:20

Hướng dẫn can we call static method from non static method javascript? - chúng ta có thể gọi phương thức tĩnh từ javascript không phương thức tĩnh không?

Mù quángBlindy

62.4K10 Huy hiệu vàng86 Huy hiệu bạc125 Huy hiệu đồng10 gold badges86 silver badges125 bronze badges

3

Không, trong các phương thức tĩnh chung không thể gọi các phương thức thể hiện. Nó có rất ít ý nghĩa để có thể làm như vậy.

Thông báo duy nhất là không có gì ngăn chặn một phương pháp tĩnh khởi tạo một thể hiện của một lớp, tại thời điểm đó, nó có thể gọi các phương thức thể hiện theo cách thông thường.

Đã trả lời ngày 27 tháng 10 năm 2015 lúc 15:21Oct 27, 2015 at 15:21

JamiecjamiecJamiec

Huy hiệu vàng 131K1313 gold badges135 silver badges191 bronze badges

Từ khó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'
0 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.
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
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

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

// Class static initialization block
static {

}
8.

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

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

// Class static initialization block
static {

}
8 từ các phương thức không tĩnh. Bạn cần gọi họ bằng tên lớp:
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 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'
4 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'
5:
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'
6 /
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'
7

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

Chúng ta có thể gọi phương thức tĩnh từ không

Đặc điểm của phương pháp tĩnh Một phương pháp tĩnh chỉ có thể gọi các phương pháp tĩnh khác;Nó không thể gọi một phương thức phi tĩnh.Một phương thức tĩnh có thể được gọi trực tiếp từ lớp, mà không phải tạo một thể hiện của lớp.it cannot call a non-static method. A static method can be called directly from the class, without having to create an instance of the class.

Phương pháp tĩnh có thể gọi không

Không, một phương thức tĩnh không thể gọi một phương thức phi tĩnh..

Tôi có thể gọi một phương thức tĩnh bên trong một phương thức thông thường không?

Nếu bạn không có đối tượng mà chỉ gọi một phương thức tĩnh và trong phương thức đó, bạn muốn gọi một phương thức tĩnh khác trong cùng một lớp, bạn phải sử dụng bản thân ::.Vì vậy, để tránh các lỗi tiềm ẩn (và cảnh báo nghiêm ngặt), tốt hơn là sử dụng bản thân.you have to use self:: . So to avoid potential errors (and strict warnings) it is better to use self .

Có thể không

Trong phương thức không tĩnh, phương pháp có thể truy cập các thành viên dữ liệu tĩnh và phương thức tĩnh cũng như các thành viên không tĩnh và phương thức của một lớp hoặc cùng một lớp, cũng có thể thay đổi các giá trị của bất kỳ thành viên dữ liệu tĩnh nào.the method can access static data members and static methods as well as non-static members and method of another class or same class, also can change the values of any static data member.