2017-10-31 3 views
1

'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 Tooltip

를 얻을 :

getSingleton() tooltip

따라서 경로가 올바른지,하지만 여전히 나에게 오류를 제공합니다.

+0

로 사용, 그것은 소리 :'헬퍼/helpers.js'와'헬퍼/user.js'를, 그래서 당신은'require ('./helpers')'또는'require ('./helpers.js')'를 원할 것입니다. 이것이 문제가 아니라고 가정하면,'console.log (typeof Helpers)'가주는 것은 무엇입니까? 'console.log (typeof Helpers.getSingleton)'은 어떨까요? –

+2

오류가 발생하지 않더라도 코드가 작동하지 않습니다. 정적 메소드 내부의'this'는 생성자 내부에서'this'와 다른 것을 참조합니다. 또한 이것은 싱글 톤이 작동하는 방식이 아닙니다. 'getSingleton()'은 처음으로 새로운 인스턴스를 인스턴스화하고 리턴해야합니다. –

답변

2

JavaScript에서 싱글 톤 패턴을 구현하는 가장 쉬운 방법은 클래스를 전혀 내 보내지 않는 것입니다.

class Helpers {} 

let helper; 
module.exports = function() { 
    if (!helper) helpers = new Helpers(); 
    return helper; 
}; 

// loaded with 
var helpers = require('../helpers')(); // note the extra() to call it 

또는 더 나은, 우리가 자바와 같은 행동에 제한되지 않기 때문에, 단지 기능을 완전히 생략하고 할

class Helpers {} 
module.exports = new Helpers(); 

// loaded with 
var helpers = require('../helpers'); 

하지만 당신의 모듈이 수출 모두가 하나 인 경우 클래스의 인스턴스를 사용하면 처음부터 클래스를 사용할 이유가 거의 없습니다. 당신은뿐만 아니라 할 수

exports.helperMethodOne = function(){}; 
exports.helperMethodTwo = function(){}; 
exports.helperMethodThree = function(){}; 

// loaded with 
var helpers = require('../helpers'); 

또는

module.exports = { 
    helperMethodOne() {}, 
    helperMethodTwo() {}, 
    helperMethodThree() {}, 
}; 

// loaded with 
var helpers = require('../helpers'); 
0

요구 사항이 잘못되었지만 환경을 알지 못해 올바른 구문을 정확하게 설명하기 어렵습니다.

const config = require('/path/to/file');

전형적인입니다. 그래서 시도 : require(...)null 같은 다른 무언가로 확인하기 때문에

TypeError: require(...).getSingleton is not a function

null.getSingleton은 다음과 같습니다

const Helpers = require('../helpers');

당신은

'../helpers' 당신은 오류, 스크린 샷에 '../helpers.js'를 작성하지 기능이 아닙니다.


또한 정적 컨텍스트 내에서 this을 의미있게 참조 할 수 없습니다. this은 정적 멤버가 아닌 클래스 인스턴스에만 사용해야합니다.

+0

나는'../helpers'와'../helpers.js' 둘 모두를 시도했지만, 내가 보았던 것과 다른 것을 만들어서는 안됩니다. – Tvde1

+0

그런데'require()'가 null을 반환하면, '속성을 읽을 수 없습니다'getSingleton 'undefined' 오류가 발생하지 않아야합니까? – Tvde1

0

당신이 Singleton.getInstance()로 사용하기 위해 뭔가를 할 수있다; 당신이 가지고있는 것처럼

class Singleton { 
    static instance = new Singleton(); 
    static getInstance =() => Singleton.instance; 

    constructor() { 
     throw new Error('Use Singleton.getInstance()'); 
    } 
} 

module.exports = Singleton; 

또는 뭔가 더 비열한 당신의 설명에서 new Singleton()

class Singleton { 
    static instance; 
    constructor() { 
     if (!Singleton.instance) { 
      Singleton.instance = this; 
     } 
     return Singleton.instance; 
    } 
} 

module.exports = Singleton; 
관련 문제