'helpers'폴더에 helpers.js
이라는 파일이 있습니다. 내용은 다음과 같다 : ES6 클래스에서 정적 함수를 호출 할 수 없습니다
class Helpers {
constructor(config) {
if (this._singleton) {
throw new Error('A singleton has already been created.');
}
this._singleton = this;
}
/**
* Gets the singleton object.
* @returns {Helpers}
*/
static getSingleton() {
return this._singleton;
}
}
module.exports = Helpers;
그런 다음
/helpers/user.js
에서 나는 도우미의 싱글 인스턴스 (instance)에 접근 할 수 있습니다.
const helpers = require('../helpers').getSingleton();
또는
const Helpers = require('../helpers');
const helpers = Helpers.getSingleton();
내가 점점 계속 오류는 다음과 같습니다 : 이 내 코드입니다
TypeError: require(...).getSingleton is not a function
또는
TypeError: Helpers.getSingleton is not a function
내가 VSCode에 Helpers
가리키면
getSingleton()
위에 마우스를 올려 때마다 나는이 도구 설명을 얻을,이 툴팁을
를 얻을 :
따라서 경로가 올바른지,하지만 여전히 나에게 오류를 제공합니다.
로 사용, 그것은 소리 :'헬퍼/helpers.js'와'헬퍼/user.js'를, 그래서 당신은'require ('./helpers')'또는'require ('./helpers.js')'를 원할 것입니다. 이것이 문제가 아니라고 가정하면,'console.log (typeof Helpers)'가주는 것은 무엇입니까? 'console.log (typeof Helpers.getSingleton)'은 어떨까요? –
오류가 발생하지 않더라도 코드가 작동하지 않습니다. 정적 메소드 내부의'this'는 생성자 내부에서'this'와 다른 것을 참조합니다. 또한 이것은 싱글 톤이 작동하는 방식이 아닙니다. 'getSingleton()'은 처음으로 새로운 인스턴스를 인스턴스화하고 리턴해야합니다. –